﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.DirectoryServices;
using Microsoft.Web.Administration;
using System.Text.RegularExpressions;

namespace HostAssistantCore
{
    /// <summary>
    /// IIS6工具类
    /// </summary>
    public class UtilForIIS6 : UtilBase, IUtil
    {
        private AddSiteUtil addsiteUtil = new AddSiteUtil();//添加站点工具

        public int CreateSite(SiteInfo siteinfo)
        {
            int errorCode = ErrorCode.Succeed;
            if (siteinfo.SiteName != siteinfo.Username)//创建子站点
            {
                errorCode = CreateChildSite(siteinfo);
                return errorCode;
            }
            /*
             * 获取站点根目录
             */
            string rootpath = siteinfo.PhysicalPath;
            if (rootpath.EndsWith("wwwroot"))
            {
                string temp = rootpath.Substring(0, rootpath.LastIndexOf("wwwroot") - 1);
                if (!Extensions.EqualsRootPath(temp))
                {
                    rootpath = temp;
                }
            }
            try
            {
                //检测站点是否存在
                if (addsiteUtil.iSiteExist(siteinfo.SiteName))
                {
                    errorCode = ErrorCode.SiteExists;
                    return errorCode;
                }
                /*
                 * 判断用户是否存在
                 */
                if (addsiteUtil.UserExist(System.Configuration.ConfigurationManager.AppSettings.Get("cusergp"),siteinfo.Username) == ErrorCode.UserExist)
                {
                    errorCode = ErrorCode.UserExist;
                    return errorCode;
                }
                /*
                 * 判断路径是否存在
                 */
                //if (addsiteUtil.PathExist(siteinfo.PhysicalPath) == ErrorCode.PathExist)
                //{
                //    errorCode = ErrorCode.PathExist;
                //    return errorCode;
                //}
                /*
                 * 创建目录
                 */
                try
                {
                    System.IO.Directory.CreateDirectory(siteinfo.PhysicalPath);
                }
                catch
                {
                    errorCode = ErrorCode.IOEXCEPTION;
                    return errorCode;
                }
                /*
                 * 创建用户
                 */
                if (addsiteUtil.AddUser(siteinfo.Username, siteinfo.Password, System.Configuration.ConfigurationManager.AppSettings.Get("cusercomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cusergp")) == ErrorCode.UserNotAdd)
                {
                    /*
                     * 回滚目录的创建
                     */
                    if (Directory.Exists(siteinfo.PhysicalPath))
                    {
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                        if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                        {
                            //如果目录为空删除
                            System.IO.Directory.Delete(siteinfo.PhysicalPath);
                        }

                    }
                    errorCode = ErrorCode.UserNotAdd;
                    return errorCode;
                }
                if (addsiteUtil.AddUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName, siteinfo.Password + System.Configuration.ConfigurationManager.AppSettings.Get("cpoolpass"), System.Configuration.ConfigurationManager.AppSettings.Get("cpoolcomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cpoolgp")) == ErrorCode.UserNotAdd)
                {
                    /*
                     * 回滚目录的创建
                     */
                    if (Directory.Exists(siteinfo.PhysicalPath))
                    {
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                        if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                        {
                            //如果目录为空删除
                            System.IO.Directory.Delete(siteinfo.PhysicalPath);
                        }

                    }
                    /*
                     * 回滚用户删除
                     */
                    addsiteUtil.delUser(siteinfo.SiteName);
                    errorCode = ErrorCode.UserNotAdd;
                    return errorCode;
                }
                /*
                 * 设置站点文件夹权限
                 */
                addsiteUtil.icaclsSet(siteinfo.SiteName, rootpath);
                addsiteUtil.icaclsSet(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName, rootpath);
                //IIS6还要设置IIS_WPG权限
                addsiteUtil.icaclsSet("IIS_WPG", rootpath);

                /*
                * 创建应用池
                */
                if (CreateAppPool(siteinfo.SiteName, siteinfo.Password + System.Configuration.ConfigurationManager.AppSettings.Get("cpoolpass"), System.Configuration.ConfigurationManager.AppSettings.Get("cpooltype"), siteinfo.NetVersion, siteinfo.Cpulimit, siteinfo.Memeroy) != ErrorCode.Succeed)
                {
                    /*
                     * 回滚目录的创建
                     */
                    if (Directory.Exists(siteinfo.PhysicalPath))
                    {
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                        if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                        {
                            //如果目录为空删除
                            System.IO.Directory.Delete(siteinfo.PhysicalPath);
                        }

                    }
                    /*
                     * 回滚用户删除
                     */
                    addsiteUtil.delUser(siteinfo.SiteName);
                    addsiteUtil.delUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName + siteinfo.SiteName);
                    errorCode = ErrorCode.poolNotBuild;
                    return errorCode;
                }
            }
            catch { }

            var siteEntry = new DirectoryEntry("IIS://localhost/w3svc");//IIS6管理对象
            int ftpId = 0;//FTP ID
            /*
            * 创建站点
            */
            try
            {
                //启用ASP4
                this.EnableAspNet4(siteEntry);

                //检查是否已存在，顺便确定端口占用及站点ID占用情况
                var usedSiteIds = new List<int>();
                var usedHttpPorts = new List<int>();
                var usedHttpsPorts = new List<int>();
                foreach (DirectoryEntry sitechild in siteEntry.Children)
                {
                    if (!sitechild.SchemaClassName.EqualsEx("IIsWebServer"))		//IIsWebServer代表站点
                        continue;
                    try
                    {
                        usedSiteIds.Add(Convert.ToInt32(sitechild.Name));			//站点的Name是SiteId
                    }
                    catch 
                    {
                    }
                }

                //启用父目录
                //addsiteUtil.SetAspParent();

                //确定可用的站点id
                int siteId = 0;
                for (siteId = 1; siteId < 65536; ++siteId)
                {
                    if (!usedSiteIds.Contains(siteId))
                        break;
                }
                ftpId = siteId + 1;
                //建站
                var site = siteEntry.Children.Add(siteId.ToString(), "IIsWebServer");

                //设置绑定等信息
                foreach (string binding in siteinfo.Bindings)
                {
                    string domain = binding.Split(":".ToArray())[0];
                    string port = "80";
                    try
                    {
                        port = binding.Split(":".ToArray())[1];
                    }
                    catch
                    {
                        port = "80";
                    }
                    if (domain == "localhost")
                        domain = "";
                    site.Properties["ServerBindings"].Add(string.Format(":{0}:{1}", port, domain));
                }
                site.Properties["ServerComment"].Value = siteinfo.SiteName;
                site.Properties["AccessScript"][0] = true;		//允许脚本执行
                site.Properties["AccessRead"][0] = true;		//允许读
                site.Properties["LogType"].Value = "1";			//记录日志
                /*
                 * 日志格式
                 */
                string logpath = System.Configuration.ConfigurationManager.AppSettings.Get("logpath") + "\\" + siteinfo.SiteName;
                site.Properties["LogExtFileFlags"].Value = LogExtFileFlags.Date | LogExtFileFlags.Time | LogExtFileFlags.ClientIP | LogExtFileFlags.UserName | LogExtFileFlags.Method | LogExtFileFlags.UriStem | LogExtFileFlags.UriQuery | LogExtFileFlags.HttpStatus | LogExtFileFlags.BytesSent | LogExtFileFlags.UserAgent | LogExtFileFlags.Referer | LogExtFileFlags.ProtocolVersion | LogExtFileFlags.BytesRecv | LogExtFileFlags.TimeTaken;
                site.Properties["LogFileDirectory"].Value = logpath;
                /*
                * 设置最大绑定数
                */
                if (siteinfo.MaxBandwidth != "0" && siteinfo.MaxBandwidth != "-1")
                    site.Properties["MaxBandwidth"].Value = Convert.ToInt64(siteinfo.MaxBandwidth) * 1024 * 1024;
                /*
                * 设置最大连接数
                */
                if (siteinfo.MaxConnections != "0" && siteinfo.MaxConnections != "-1")
                    site.Properties["MaxConnections"].Value = Convert.ToInt64(siteinfo.MaxConnections);

                /*
                 * 设置应用程序扩展[ASP.NET版本+PHP]
                 */
                string[] setnetversion = addsiteUtil._GetAspNetVersion(siteinfo.Phppath, siteinfo.NetVersion,siteId);
                site.Properties["ScriptMaps"].Value = setnetversion;

                //<IIsFilters	Location ="/LM/W3SVC/10002/Filters"
                //    FilterLoadOrder=""
                //>
                //建根目录
                var root = site.Children.Add("ROOT", "IIsWebVirtualDir");
                root.Properties["Path"].Value = siteinfo.PhysicalPath;
                root.Properties["AppIsolated"].Value = "1";
                root.Properties["AppRoot"].Value = "/LM/W3SVC/" + siteId + "/Root";
                /*
                * 设置站点访问权限
                */
                site.Properties["AnonymousUserName"].Value = siteinfo.SiteName;//这里是系统用户
                site.Properties["AnonymousUserPass"].Value = siteinfo.Password;//对应的密码
                root.Properties["AnonymousUserName"].Value = siteinfo.SiteName;//这里是系统用户
                root.Properties["AnonymousUserPass"].Value = siteinfo.Password;//对应的密码 
                root.Properties["AppFriendlyName"].Value = siteinfo.SiteName;//用户的友好显示  
                root.Properties["AppPoolId"].Value = siteinfo.SiteName;
                root.Properties["AspEnableParentPaths"].Value = true;
                root.Properties["ScriptMaps"].Value = setnetversion;
                //建Filters
                //var filters = site.Children.Add("Filters", "IIsWebVirtualDir");

                /*
                 * 设置默认文档
                 */
                string defaultDocuments = "";
                if (siteinfo.DefaultDocuments.Count != 0)
                {
                    foreach (string defaultDocument in siteinfo.DefaultDocuments)
                    {
                        defaultDocuments += defaultDocument + ",";
                    }
                }
                defaultDocuments = defaultDocuments.Substring(0, defaultDocuments.Length - 1);
                root.Properties["DefaultDoc"].Value = defaultDocuments;
                //提交更改
                site.CommitChanges();
                root.CommitChanges();
                //filters.CommitChanges();
                try
                {
                    site.Invoke("Start", new object[] { });//启动站点
                }
                catch
                {
                    errorCode = ErrorCode.siteStateError;
                }
                siteEntry.CommitChanges();
                /*
                * 指定应用程序池
                */
                //addsiteUtil.connectPool(siteinfo.SiteName, siteinfo.SiteName);
            }
            catch
            {
                /*
                * 回滚目录的创建
                */
                if (Directory.Exists(siteinfo.PhysicalPath))
                {
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                    if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                    {
                        //如果目录为空删除
                        System.IO.Directory.Delete(siteinfo.PhysicalPath);
                    }
                }
                /*
                 * 回滚用户删除
                 */
                addsiteUtil.delUser(siteinfo.SiteName);
                addsiteUtil.delUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName + siteinfo.SiteName);
                /*
                 * 撤销更改
                 */
                siteEntry.Dispose();
                errorCode = ErrorCode.CommitFail;
                return errorCode;
            }
            /*
            * 设置站点限制
            */
            /*
            * 创建FTP
            */
            if (siteinfo.Password != System.Configuration.ConfigurationManager.AppSettings.Get("defaultpassword"))
            {
                FtpUtil ftputil = new FtpUtil();
                ftputil.icreateFtpPoint(siteinfo.SiteName, rootpath, ftpId);
            }
            /*
            * 将新建的站点数据存储到数据库表
            */
            if (IISAdoHelper.adoSaveNewSite(siteinfo.SiteName) == ErrorCode.saveNewSiteFail)
            {
                errorCode = ErrorCode.saveNewSiteFail;
            }
            /*
            * 复制Hello页面到站点目录
            */
            string yrootpath = System.Environment.CurrentDirectory;
            string hellopath = yrootpath + "/conf/" + "hello.htm";
            string sitepath = System.IO.Path.Combine(@siteinfo.PhysicalPath, System.IO.Path.GetFileName(@hellopath));
            System.IO.File.Copy(@hellopath, sitepath, true);

            return errorCode;
        }

        public int R_CreateSite(SiteInfo siteinfo)
        {
            //pool flag
            bool pool_flag = true;
            int errorCode = ErrorCode.Succeed;
            if (siteinfo.SiteName != siteinfo.Username)//创建子站点
            {
                errorCode = CreateChildSite(siteinfo);
                return errorCode;
            }
            /*
             * 获取站点根目录
             */
            string rootpath = siteinfo.PhysicalPath;
            if (rootpath.EndsWith("wwwroot"))
            {
                string temp = rootpath.Substring(0, rootpath.LastIndexOf("wwwroot") - 1);
                if (!Extensions.EqualsRootPath(temp))
                {
                    rootpath = temp;
                }
            }
            try
            {
                //检测站点是否存在
                if (addsiteUtil.iSiteExist(siteinfo.SiteName))
                {
                    errorCode = ErrorCode.SiteExists;
                    return errorCode;
                }
                /*
                 * 判断用户是否存在
                 */
                if (addsiteUtil.UserExist(System.Configuration.ConfigurationManager.AppSettings.Get("cusergp"), siteinfo.Username) == ErrorCode.UserExist)
                {
                    errorCode = ErrorCode.UserExist;
                    return errorCode;
                }
                /*
                 * 判断路径是否存在
                 */
                //if (addsiteUtil.PathExist(siteinfo.PhysicalPath) == ErrorCode.PathExist)
                //{
                //    errorCode = ErrorCode.PathExist;
                //    return errorCode;
                //}
                /*
                 * 创建目录
                 */
                try
                {
                    System.IO.Directory.CreateDirectory(siteinfo.PhysicalPath);
                }
                catch
                {
                    errorCode = ErrorCode.IOEXCEPTION;
                    return errorCode;
                }
                /*
                 * 创建用户
                 */
                if (addsiteUtil.AddUser(siteinfo.SiteName, siteinfo.Password, System.Configuration.ConfigurationManager.AppSettings.Get("cusercomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cusergp")) == ErrorCode.UserNotAdd)
                {
                    /*
                     * 回滚目录的创建
                     */
                    if (Directory.Exists(siteinfo.PhysicalPath))
                    {
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                        if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                        {
                            //如果目录为空删除
                            System.IO.Directory.Delete(siteinfo.PhysicalPath);
                        }

                    }
                    errorCode = ErrorCode.UserNotAdd;
                    return errorCode;
                }
                if (siteinfo.SiteName.Length > 16)
                {
                    pool_flag = false;
                }
                else
                {
                    if (addsiteUtil.AddUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName, siteinfo.Password + System.Configuration.ConfigurationManager.AppSettings.Get("cpoolpass"), System.Configuration.ConfigurationManager.AppSettings.Get("cpoolcomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cpoolgp")) == ErrorCode.UserNotAdd)
                    {
                        /*
                         * 回滚目录的创建
                         */
                        if (Directory.Exists(siteinfo.PhysicalPath))
                        {
                            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                            if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                            {
                                //如果目录为空删除
                                System.IO.Directory.Delete(siteinfo.PhysicalPath);
                            }

                        }
                        /*
                         * 回滚用户删除
                         */
                        addsiteUtil.delUser(siteinfo.SiteName);
                        errorCode = ErrorCode.UserNotAdd;
                        return errorCode;
                    }
                }
                /*
                 * 设置站点文件夹权限
                 */
                addsiteUtil.icaclsSet(siteinfo.SiteName, rootpath);
                addsiteUtil.icaclsSet(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName, rootpath);
                //IIS6还要设置IIS_WPG权限
                addsiteUtil.icaclsSet("IIS_WPG", rootpath);

                /*
                * 创建应用池
                */
                if (pool_flag)
                {
                    if (CreateAppPool(siteinfo.Username, siteinfo.Password + System.Configuration.ConfigurationManager.AppSettings.Get("cpoolpass"), System.Configuration.ConfigurationManager.AppSettings.Get("cpooltype"), siteinfo.NetVersion, siteinfo.Cpulimit, siteinfo.Memeroy) != ErrorCode.Succeed)
                    {
                        /*
                         * 回滚目录的创建
                         */
                        if (Directory.Exists(siteinfo.PhysicalPath))
                        {
                            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                            if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                            {
                                //如果目录为空删除
                                System.IO.Directory.Delete(siteinfo.PhysicalPath);
                            }

                        }
                        /*
                         * 回滚用户删除
                         */
                        addsiteUtil.delUser(siteinfo.SiteName);
                        addsiteUtil.delUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName + siteinfo.SiteName);
                        errorCode = ErrorCode.poolNotBuild;
                        return errorCode;
                    }
                }
            }
            catch { }

            var siteEntry = new DirectoryEntry("IIS://localhost/w3svc");//IIS6管理对象
            int ftpId = 0;//FTP ID
            /*
            * 创建站点
            */
            try
            {
                //启用ASP4
                this.EnableAspNet4(siteEntry);

                //检查是否已存在，顺便确定端口占用及站点ID占用情况
                var usedSiteIds = new List<int>();
                var usedHttpPorts = new List<int>();
                var usedHttpsPorts = new List<int>();
                foreach (DirectoryEntry sitechild in siteEntry.Children)
                {
                    if (!sitechild.SchemaClassName.EqualsEx("IIsWebServer"))		//IIsWebServer代表站点
                        continue;
                    try
                    {
                        usedSiteIds.Add(Convert.ToInt32(sitechild.Name));			//站点的Name是SiteId
                    }
                    catch
                    {
                    }
                }

                //启用父目录
                //addsiteUtil.SetAspParent();

                //确定可用的站点id
                int siteId = 0;
                for (siteId = 1; siteId < 65536; ++siteId)
                {
                    if (!usedSiteIds.Contains(siteId))
                        break;
                }
                ftpId = siteId + 1;
                //建站
                var site = siteEntry.Children.Add(siteId.ToString(), "IIsWebServer");

                //设置绑定等信息
                foreach (string binding in siteinfo.Bindings)
                {
                    string domain = binding.Split(":".ToArray())[0];
                    string port = "80";
                    try
                    {
                        port = binding.Split(":".ToArray())[1];
                    }
                    catch
                    {
                        port = "80";
                    }
                    if (domain == "localhost")
                        domain = "";
                    site.Properties["ServerBindings"].Add(string.Format(":{0}:{1}", port, domain));
                }
                site.Properties["ServerComment"].Value = siteinfo.SiteName;
                site.Properties["AccessScript"][0] = true;		//允许脚本执行
                site.Properties["AccessRead"][0] = true;		//允许读
                site.Properties["LogType"].Value = "1";			//记录日志
                /*
                 * 日志格式
                 */
                string logpath = System.Configuration.ConfigurationManager.AppSettings.Get("logpath") + "\\" + siteinfo.SiteName;
                site.Properties["LogExtFileFlags"].Value = LogExtFileFlags.Date | LogExtFileFlags.Time | LogExtFileFlags.ClientIP | LogExtFileFlags.UserName | LogExtFileFlags.Method | LogExtFileFlags.UriStem | LogExtFileFlags.UriQuery | LogExtFileFlags.HttpStatus | LogExtFileFlags.BytesSent | LogExtFileFlags.UserAgent | LogExtFileFlags.Referer | LogExtFileFlags.ProtocolVersion | LogExtFileFlags.BytesRecv | LogExtFileFlags.TimeTaken;
                site.Properties["LogFileDirectory"].Value = logpath;
                /*
                * 设置最大绑定数
                */
                if (siteinfo.MaxBandwidth != "0" && siteinfo.MaxBandwidth != "-1")
                    site.Properties["MaxBandwidth"].Value = Convert.ToInt64(siteinfo.MaxBandwidth) * 1024 * 1024;
                /*
                * 设置最大连接数
                */
                if (siteinfo.MaxConnections != "0" && siteinfo.MaxConnections != "-1")
                    site.Properties["MaxConnections"].Value = Convert.ToInt64(siteinfo.MaxConnections);

                /*
                 * 设置应用程序扩展[ASP.NET版本+PHP]
                 */
                string[] setnetversion = addsiteUtil._GetAspNetVersion(siteinfo.Phppath, siteinfo.NetVersion, siteId);
                site.Properties["ScriptMaps"].Value = setnetversion;

                //<IIsFilters	Location ="/LM/W3SVC/10002/Filters"
                //    FilterLoadOrder=""
                //>
                //建根目录
                var root = site.Children.Add("ROOT", "IIsWebVirtualDir");
                root.Properties["Path"].Value = siteinfo.PhysicalPath;
                root.Properties["AppIsolated"].Value = "1";
                root.Properties["AppRoot"].Value = "/LM/W3SVC/" + siteId + "/Root";
                /*
                * 设置站点访问权限
                */
                site.Properties["AnonymousUserName"].Value = siteinfo.SiteName;//这里是系统用户
                site.Properties["AnonymousUserPass"].Value = siteinfo.Password;//对应的密码
                root.Properties["AnonymousUserName"].Value = siteinfo.SiteName;//这里是系统用户
                root.Properties["AnonymousUserPass"].Value = siteinfo.Password;//对应的密码 
                root.Properties["AppFriendlyName"].Value = siteinfo.SiteName;//用户的友好显示  
                if (pool_flag)
                {
                    root.Properties["AppPoolId"].Value = siteinfo.SiteName;
                }
                root.Properties["AspEnableParentPaths"].Value = true;
                root.Properties["ScriptMaps"].Value = setnetversion;
                //建Filters
                //var filters = site.Children.Add("Filters", "IIsWebVirtualDir");

                /*
                 * 设置默认文档
                 */
                string defaultDocuments = "";
                if (siteinfo.DefaultDocuments.Count != 0)
                {
                    foreach (string defaultDocument in siteinfo.DefaultDocuments)
                    {
                        defaultDocuments += defaultDocument + ",";
                    }
                }
                defaultDocuments = defaultDocuments.Substring(0, defaultDocuments.Length - 1);
                root.Properties["DefaultDoc"].Value = defaultDocuments;
                //filters.CommitChanges();
                siteEntry.CommitChanges();
                try
                {
                    site.Invoke("Start", new object[] { });//启动站点
                }
                catch
                {
                    errorCode = ErrorCode.siteStateError;
                }
                //提交更改
                site.CommitChanges();
                root.CommitChanges();
                /*
                * 指定应用程序池
                */
                //addsiteUtil.connectPool(siteinfo.SiteName, siteinfo.SiteName);
            }
            catch
            {
                /*
                * 回滚目录的创建
                */
                if (Directory.Exists(siteinfo.PhysicalPath))
                {
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                    if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                    {
                        //如果目录为空删除
                        System.IO.Directory.Delete(siteinfo.PhysicalPath);
                    }
                }
                /*
                 * 回滚用户删除
                 */
                addsiteUtil.delUser(siteinfo.SiteName);
                addsiteUtil.delUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName + siteinfo.SiteName);
                /*
                 * 撤销更改
                 */
                siteEntry.Dispose();
                errorCode = ErrorCode.CommitFail;
                return errorCode;
            }
            /*
            * 设置站点限制
            */
            /*
            * 创建FTP
            */
            if (siteinfo.Password != System.Configuration.ConfigurationManager.AppSettings.Get("defaultpassword"))
            {
                FtpUtil ftputil = new FtpUtil();
                ftputil.icreateFtpPoint(siteinfo.SiteName, rootpath, ftpId);
            }
            /*
            * 将新建的站点数据存储到数据库表
            */
            if (IISAdoHelper.adoSaveNewSite(siteinfo.SiteName) == ErrorCode.saveNewSiteFail)
            {
                errorCode = ErrorCode.saveNewSiteFail;
            }
            /*
            * 复制Hello页面到站点目录
            */
            string yrootpath = System.Environment.CurrentDirectory;
            string hellopath = yrootpath + "/conf/" + "hello.htm";
            string sitepath = System.IO.Path.Combine(@siteinfo.PhysicalPath, System.IO.Path.GetFileName(@hellopath));
            System.IO.File.Copy(@hellopath, sitepath, true);

            return errorCode;
        }

        #region 创建子站点
        /// <summary>
        /// 创建站点的子站点
        /// </summary>
        /// <param name="siteinfo"></param>
        /// <returns></returns>
        public int CreateChildSite(SiteInfo siteinfo)
        {
            int errorCode = ErrorCode.Succeed;
            string sitename = siteinfo.Username;
            string password = siteinfo.Password;
            try
            {
                //检测站点是否存在
                if (addsiteUtil.iSiteExist(siteinfo.SiteName))
                {
                    errorCode = ErrorCode.SiteExists;
                    return errorCode;
                }
                /*
                 * 判断路径是否存在
                 */
                //if (addsiteUtil.PathExist(siteinfo.PhysicalPath) == ErrorCode.PathExist)
                //{
                //    errorCode = ErrorCode.PathExist;
                //    return errorCode;
                //}
                /*
                 * 创建目录
                 */
                try
                {
                    System.IO.Directory.CreateDirectory(siteinfo.PhysicalPath);
                }
                catch
                {
                    errorCode = ErrorCode.IOEXCEPTION;
                    return errorCode;
                }
            }
            catch { }

            var siteEntry = new DirectoryEntry("IIS://localhost/w3svc");//IIS6管理对象
            /*
            * 创建站点
            */
            try
            {
                //启用ASP4
                this.EnableAspNet4(siteEntry);

                //检查是否已存在，顺便确定端口占用及站点ID占用情况
                var usedSiteIds = new List<int>();
                var usedHttpPorts = new List<int>();
                var usedHttpsPorts = new List<int>();
                foreach (DirectoryEntry sitechild in siteEntry.Children)
                {
                    if (!sitechild.SchemaClassName.EqualsEx("IIsWebServer"))		//IIsWebServer代表站点
                        continue;
                    try
                    {
                        usedSiteIds.Add(Convert.ToInt32(sitechild.Name));			//站点的Name是SiteId
                    }
                    catch
                    {
                    }
                }

                //启用父目录
                //addsiteUtil.SetAspParent();

                //确定可用的站点id
                int siteId = 0;
                for (siteId = 1; siteId < 65536; ++siteId)
                {
                    if (!usedSiteIds.Contains(siteId))
                        break;
                }
                //建站
                var site = siteEntry.Children.Add(siteId.ToString(), "IIsWebServer");

                //设置绑定等信息
                foreach (string binding in siteinfo.Bindings)
                {
                    string domain = binding.Split(":".ToArray())[0];
                    string port = "80";
                    try
                    {
                        port = binding.Split(":".ToArray())[1];
                    }
                    catch
                    {
                        port = "80";
                    }
                    if (domain == "localhost")
                        domain = "";
                    site.Properties["ServerBindings"].Add(string.Format(":{0}:{1}", port, domain));
                }
                site.Properties["ServerComment"].Value = siteinfo.SiteName;
                site.Properties["AccessScript"][0] = true;		//允许脚本执行
                site.Properties["AccessRead"][0] = true;		//允许读
                site.Properties["LogType"].Value = "1";			//记录日志
                /*
                 * 日志格式
                 */
                string logpath = System.Configuration.ConfigurationManager.AppSettings.Get("logpath") + "\\" + siteinfo.SiteName;
                site.Properties["LogExtFileFlags"].Value = LogExtFileFlags.Date | LogExtFileFlags.Time | LogExtFileFlags.ClientIP | LogExtFileFlags.UserName | LogExtFileFlags.Method | LogExtFileFlags.UriStem | LogExtFileFlags.UriQuery | LogExtFileFlags.HttpStatus | LogExtFileFlags.BytesSent | LogExtFileFlags.UserAgent | LogExtFileFlags.Referer | LogExtFileFlags.ProtocolVersion | LogExtFileFlags.BytesRecv | LogExtFileFlags.TimeTaken;
                site.Properties["LogFileDirectory"].Value = logpath;
                /*
                * 设置最大绑定数
                */
                if (siteinfo.MaxBandwidth != "0" && siteinfo.MaxBandwidth != "-1")
                    site.Properties["MaxBandwidth"].Value = Convert.ToInt64(siteinfo.MaxBandwidth) * 1024 * 1024;
                /*
                * 设置最大连接数
                */
                if (siteinfo.MaxConnections != "0" && siteinfo.MaxConnections != "-1")
                    site.Properties["MaxConnections"].Value = Convert.ToInt64(siteinfo.MaxConnections);

                /*
                 * 设置应用程序扩展[ASP.NET版本+PHP]
                 */
                string[] setnetversion = addsiteUtil._GetAspNetVersion(siteinfo.Phppath, siteinfo.NetVersion, siteId);
                site.Properties["ScriptMaps"].Value = setnetversion;

                //<IIsFilters	Location ="/LM/W3SVC/10002/Filters"
                //    FilterLoadOrder=""
                //>
                //建根目录
                var root = site.Children.Add("ROOT", "IIsWebVirtualDir");
                root.Properties["Path"].Value = siteinfo.PhysicalPath;
                root.Properties["AppIsolated"].Value = "1";
                root.Properties["AppRoot"].Value = "/LM/W3SVC/" + siteId + "/Root";
                /*
                * 设置站点访问权限
                */
                site.Properties["AnonymousUserName"].Value = sitename;//这里是系统用户  
                site.Properties["AnonymousUserPass"].Value = password;//对应的密码  
                root.Properties["AnonymousUserName"].Value = sitename;//这里是系统用户  
                root.Properties["AnonymousUserPass"].Value = password;//对应的密码  
                root.Properties["AppFriendlyName"].Value = sitename;//用户的友好显示  
                root.Properties["AppPoolId"].Value = sitename;
                root.Properties["AspEnableParentPaths"].Value = true;
                root.Properties["ScriptMaps"].Value = setnetversion;
                //建Filters
                //var filters = site.Children.Add("Filters", "IIsWebVirtualDir");
                /*
                 * 设置默认文档
                 */
                string defaultDocuments = "";
                if (siteinfo.DefaultDocuments.Count != 0)
                {
                    foreach (string defaultDocument in siteinfo.DefaultDocuments)
                    {
                        defaultDocuments += defaultDocument + ",";
                    }
                }
                defaultDocuments = defaultDocuments.Substring(0, defaultDocuments.Length - 1);
                root.Properties["DefaultDoc"].Value = defaultDocuments;
                //提交更改
                site.CommitChanges();
                root.CommitChanges();
                try
                {
                    site.Invoke("Start", new object[] { });//启动站点
                }
                catch
                {
                    errorCode = ErrorCode.siteStateError;
                }
                //filters.CommitChanges();
                siteEntry.CommitChanges();
                /*
                * 指定应用程序池
                */
                //addsiteUtil.connectPool(siteinfo.SiteName, siteinfo.SiteName);
            }
            catch
            {
                /*
                * 回滚目录的创建
                */
                if (Directory.Exists(siteinfo.PhysicalPath))
                {
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                    if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                    {
                        //如果目录为空删除
                        System.IO.Directory.Delete(siteinfo.PhysicalPath);
                    }
                }
                /*
                 * 撤销更改
                 */
                siteEntry.Dispose();
                errorCode = ErrorCode.CommitFail;
                return errorCode;
            }
            /*
            * 将新建的站点数据存储到数据库表
            */
            if (IISAdoHelper.adoSaveNewSite(siteinfo.SiteName) == ErrorCode.saveNewSiteFail)
            {
                errorCode = ErrorCode.saveNewSiteFail;
            }
            /*
            * 复制Hello页面到站点目录
            */
            string yrootpath = System.Environment.CurrentDirectory;
            string hellopath = yrootpath + "/conf/" + "hello.htm";
            string sitepath = System.IO.Path.Combine(@siteinfo.PhysicalPath, System.IO.Path.GetFileName(@hellopath));
            System.IO.File.Copy(@hellopath, sitepath, true);

            return errorCode;
        }
        #endregion

        /// <summary>
        /// 编辑站点
        /// </summary>
        /// <param name="siteinfo"></param>
        /// <returns></returns>
        public int SetSite(SiteInfo siteinfo)
        {
            int errorCode = ErrorCode.SetSucceed;
            var siteEntry = new DirectoryEntry("IIS://localhost/w3svc");//IIS6管理对象
            var poolEntry = new DirectoryEntry("IIS://localhost/w3svc/apppools");//pool
            var ftpEntry = new DirectoryEntry("IIS://localhost/MSFTPSVC");//FTP管理对象
            try
            {
                foreach (DirectoryEntry child in siteEntry.Children)
                {
                    if (child.SchemaClassName == "IIsWebServer" && child.Properties["ServerComment"].Value.ToString() == siteinfo.SiteName)
                    {
                        /*---- pool connect ----*/
                        bool poolset_flag = false;
                        /*
                        * 更改ftp密码
                         * 先判断是否存在该ftp站点 不存在创建
                        * 只要更改用户密码
                        * 还要更改站点密码
                        */
                        if (siteinfo.Password != "")
                        {
                            //判断用户是否存在 不存在 添加
                            if (!ADUser.ExistUser(siteinfo.SiteName))
                            {
                                /*
                                * 创建用户
                                */
                                addsiteUtil.AddUser(siteinfo.SiteName, siteinfo.Password, System.Configuration.ConfigurationManager.AppSettings.Get("cusercomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cusergp"));
                            }
                            else
                            {
                                ADUser.PwdModify(siteinfo.SiteName, siteinfo.Password);
                            }
                            if (!ADUser.ExistUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName))
                            {
                                /*
                                * 创建用户
                                */
                                addsiteUtil.AddUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName, siteinfo.Password + System.Configuration.ConfigurationManager.AppSettings.Get("cpoolpass"), System.Configuration.ConfigurationManager.AppSettings.Get("cpoolcomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cpoolgp"));
                                /*
                                * 创建应用池
                                */
                                CreateAppPool_Q(siteinfo.SiteName, siteinfo.Password + System.Configuration.ConfigurationManager.AppSettings.Get("cpoolpass"));
                                poolset_flag = true;
                            }
                            try
                            {
                                FtpUtil ftputil = new FtpUtil();
                                if (!ftputil.igetFtpState(siteinfo.SiteName))
                                {
                                    /*
                                    * 获取站点根目录
                                    */
                                    string rootpath = siteinfo.PhysicalPath;
                                    if (rootpath.EndsWith("wwwroot"))
                                    {
                                        string temp = rootpath.Substring(0, rootpath.LastIndexOf("wwwroot") - 1);
                                        if (!Extensions.EqualsRootPath(temp))
                                        {
                                            rootpath = temp;
                                        }
                                    }
                                    //创建FTP站点 
                                    //检查是否已存在，顺便确定端口占用及站点ID占用情况
                                    var usedSiteIds = new List<int>();
                                    foreach (DirectoryEntry sitechild in siteEntry.Children)
                                    {
                                        if (!sitechild.SchemaClassName.EqualsEx("IIsWebServer"))        //IIsWebServer代表站点
                                            continue;

                                        usedSiteIds.Add(Convert.ToInt32(sitechild.Name));           //站点的Name是SiteId
                                    }

                                    int ftpId = 0;//FTP ID
                                    for (ftpId = 1; ftpId < 65536; ++ftpId)
                                    {
                                        if (!usedSiteIds.Contains(ftpId))
                                            break;
                                    }
                                    /*
                                     * 设置站点文件夹权限
                                     */
                                    if (!addsiteUtil.FileSP_Exists(rootpath, siteinfo.SiteName))
                                    {
                                        addsiteUtil.icaclsSet(siteinfo.SiteName, rootpath);
                                    }
                                    if (!addsiteUtil.FileSP_Exists(rootpath, System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName))
                                    {
                                        addsiteUtil.icaclsSet(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName, rootpath);
                                    }
                                    ftputil.icreateFtpPoint(siteinfo.SiteName, rootpath, ftpId);
                                }
                            }
                            catch
                            {

                            }
                            child.Properties["AnonymousUserPass"].Value = siteinfo.Password;
                        }
                        /*
                        * 设置日志路径
                        */
                        if (siteinfo.PhysicalPath != "")
                        {
                            string disk = siteinfo.PhysicalPath.Substring(0, 1);
                            string logpath = disk + System.Configuration.ConfigurationManager.AppSettings.Get("logpath").Substring(1, System.Configuration.ConfigurationManager.AppSettings.Get("logpath").Length - 1) + "\\" + siteinfo.SiteName;
                            if (!Directory.Exists(logpath))
                            {
                                Directory.CreateDirectory(logpath);
                            }
                            child.Properties["LogFileDirectory"].Value = logpath;
                            // set priviliges
                            addsiteUtil.icaclsSet(siteinfo.SiteName, siteinfo.PhysicalPath);
                            addsiteUtil.icaclsSet(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName, siteinfo.PhysicalPath);
                        }
                        /*
                        * 设置绑定信息
                        */
                        if (siteinfo.Bindings != null)
                        {
                            /*
                             * 删除所有绑定
                             */
                            int bindscount = child.Properties["ServerBindings"].Count;
                            for (int i = 0; i < bindscount; i++)
                            {
                                child.Properties["ServerBindings"].RemoveAt(0);
                            }
                            foreach (string binding in siteinfo.Bindings)
                            {
                                string domain = binding.Split(":".ToArray())[0];
                                string port = "80";
                                try
                                {
                                    port = binding.Split(":".ToArray())[1];
                                }
                                catch
                                {
                                    port = "80";
                                }
                                if (domain == "localhost")
                                    domain = "";
                                child.Properties["ServerBindings"].Add(string.Format(":{0}:{1}", port, domain));
                            }
                        }
                        /*
                        * 修改.net版本和php引擎
                        */
                        if (siteinfo.MaxBandwidth != "0" && siteinfo.MaxBandwidth != "-1")
                        {
                            child.Properties["MaxBandwidth"].Value = Convert.ToInt64(siteinfo.MaxBandwidth) * 1024 * 1024 ;
                        }
                        if (siteinfo.MaxConnections != "0" && siteinfo.MaxConnections != "-1")
                        {
                            child.Properties["MaxConnections"].Value = Convert.ToInt64(siteinfo.MaxConnections);
                        }
                        string[] setnetversion = addsiteUtil._GetAspNetVersion(siteinfo.Phppath, siteinfo.NetVersion, Convert.ToInt32(child.Name));
                        child.Properties["ScriptMaps"].Value = setnetversion;

                        /*
                        * 设置限制
                        */
                        foreach (DirectoryEntry rootChild in child.Children)
                        {
                            string name = rootChild.Name.ToString();
                            if ((rootChild.SchemaClassName == "IIsWebVirtualDir") && (rootChild.Name.ToString().ToLower() == "root"))
                            {
                                /*
                                 * bind app pool
                                 */
                                if (poolset_flag)
                                {
                                    rootChild.Properties["AppPoolId"].Value = siteinfo.SiteName;
                                }
                                /*
                                 * 站点路径
                                 */
                                if (siteinfo.PhysicalPath != "")
                                {
                                    if (!Directory.Exists(siteinfo.PhysicalPath))
                                    {
                                        Directory.CreateDirectory(siteinfo.PhysicalPath);
                                    }
                                    rootChild.Properties["Path"].Value = siteinfo.PhysicalPath;
                                }
                                /*
                                 * 修改主页
                                 */
                                if (siteinfo.DefaultDocuments != null)
                                {
                                    string DefaultDoc = null;
                                    foreach (string defaultDocument in siteinfo.DefaultDocuments)
                                    {
                                        DefaultDoc += defaultDocument + ",";
                                    }
                                    DefaultDoc = DefaultDoc.Substring(0, DefaultDoc.Length - 1);
                                    rootChild.Properties["DefaultDoc"].Value = DefaultDoc;
                                }
                                /*
                                 * 同样的设置虚拟目录的ASP和PHP引擎
                                 */
                                rootChild.Properties["ScriptMaps"].Value = setnetversion;
                                rootChild.CommitChanges();
                            }
                        }
                        child.CommitChanges();
                    }
                }
                /*
                 * 设置cpu和内存限制
                 */
                foreach (DirectoryEntry pool in poolEntry.Children)
                {
                    //IIsApplicationPool表示应用程序池，Name即为名称
                    if (pool.Name.EqualsEx(siteinfo.SiteName) && pool.SchemaClassName.EqualsEx("IIsApplicationPool"))
                    {
                        if (siteinfo.Cpulimit != "0")
                        {
                            pool.Properties["CPULimit"].Value = Convert.ToInt32(siteinfo.Cpulimit) * 1000;
                        }
                        if (siteinfo.Memeroy != "0")
                        {
                            pool.Properties["PeriodicRestartMemory"].Value = Convert.ToInt32(siteinfo.Memeroy) * 1024;
                            pool.Properties["PeriodicRestartPrivateMemory"].Value = Convert.ToInt32(siteinfo.Memeroy) * 1024;
                        }
                        pool.CommitChanges();
                    }
                }
                /*
                * 将新建的站点数据存储到数据库表
                */
                if (IISAdoHelper.adoSaveNowSite(siteinfo.SiteName) == ErrorCode.saveNewSiteFail)
                {
                    errorCode = ErrorCode.saveNewSiteFail;
                }
            }
            catch
            {
                errorCode = ErrorCode.SetFail;
            }
            return errorCode;
        }

        public int CreateSite(string siteName, int httpPort, int httpsPort, string sslHash, string physicalPath)
        {
            int errorCode = ErrorCode.Succeed;

            try
            {
                var siteEntry = new DirectoryEntry("IIS://localhost/w3svc");

                //启用ASP4
                this.EnableAspNet4(siteEntry);

                //检查是否已存在，顺便确定端口占用及站点ID占用情况
                bool exists = false;
                var usedSiteIds = new List<int>();
                var usedHttpPorts = new List<int>();
                var usedHttpsPorts = new List<int>();
                foreach (DirectoryEntry site in siteEntry.Children)
                {
                    if (!site.SchemaClassName.EqualsEx("IIsWebServer"))		//IIsWebServer代表站点
                        continue;

                    usedSiteIds.Add(Convert.ToInt32(site.Name));			//站点的Name是SiteId
                    usedHttpPorts.Add(GetPort(site.Properties["ServerBindings"].Value as string));
                    usedHttpsPorts.Add(GetPort(site.Properties["SecureBindings"].Value as string));

                    string name = Convert.ToString(site.Properties["ServerComment"].Value);
                    if (!name.IsNullOrEmpty() && name.EqualsEx(siteName))
                        exists = true;
                }

                //不存在才创建
                if (!exists)
                {
                    //检查端口占用情况
                    if (httpPort > 0 && usedHttpPorts.Contains(httpPort))
                    {
                        //http端口占用
                        errorCode = ErrorCode.HttpPortUsed;
                    }
                    else if (httpsPort > 0 && usedHttpsPorts.Contains(httpsPort))
                    {
                        //https端口占用
                        errorCode = ErrorCode.HttpsPortUsed;
                    }
                    else
                    {
                        //确定可用的站点id
                        int siteId = 0;
                        for (siteId = 1; siteId < 65536; ++siteId)
                        {
                            if (!usedSiteIds.Contains(siteId))
                                break;
                        }

                        //建站
                        var site = siteEntry.Children.Add(siteId.ToString(), "IIsWebServer");

                        //设置绑定等信息
                        site.Properties["ServerBindings"].Value = string.Format(":{0}:", httpPort);
                        site.Properties["ServerComment"].Value = siteName;
                        site.Properties["AccessScript"][0] = true;		//允许脚本执行
                        site.Properties["AccessRead"][0] = true;		//允许读
                        site.Properties["LogType"].Value = "0";			//不记录日志
                        if (httpsPort > 0)
                        {
                            site.Properties["SecureBindings"].Value = string.Format(":{0}:", httpsPort);
                            site.Properties["SSLStoreName"][0] = "MY";	//个人存储区

                            //ssl信息必须以特殊的格式加入
                            var hash = new object[sslHash.Length / 2];
                            for (int i = 0; i < sslHash.Length / 2; ++i)
                                hash[i] = sslHash.Substring(i * 2, 2);
                            site.Properties["SSLCertHash"].Clear();
                            site.Properties["SSLCertHash"].Add(hash);
                        }

                        //建根目录
                        var root = site.Children.Add("ROOT", "IIsWebVirtualDir");
                        root.Properties["Path"].Value = physicalPath;

                        root.CommitChanges();
                        site.CommitChanges();
                    }
                }
                else
                {
                    errorCode = ErrorCode.SiteExists;
                }
            }
            catch (Exception ex)
            {
                errorCode = ErrorCode.Unknown;
                Console.WriteLine(ex.Message);
            }

            return errorCode;
        }

        public int RemoveSite(string siteName)
        {
            int errorCode = ErrorCode.Succeed;

            try
            {
                var siteEntry = new DirectoryEntry("IIS://localhost/w3svc");

                //找指定站点
                DirectoryEntry targetSite = null;
                foreach (DirectoryEntry site in siteEntry.Children)
                {
                    if (!site.SchemaClassName.EqualsEx("IIsWebServer"))
                        continue;

                    //站点名在ServerComment中
                    string name = Convert.ToString(site.Properties["ServerComment"].Value);
                    if (!name.IsNullOrEmpty() && name.EqualsEx(siteName))
                    {
                        targetSite = site;
                        break;
                    }
                }

                //存在才移除
                if (targetSite != null)
                {
                    siteEntry.Children.Remove(targetSite);
                    siteEntry.CommitChanges();
                }
                else
                {
                    errorCode = ErrorCode.SiteNotFound;
                }
            }
            catch (Exception ex)
            {
                errorCode = ErrorCode.Unknown;
                Console.WriteLine(ex.Message);
            }

            return errorCode;
        }

        public int CreateAppPool(string poolName, string password, string pooltype, string netversion, string cpulimit, string memeory)
        {
            int errorCode = ErrorCode.Succeed;

            try
            {
                var poolEntry = new DirectoryEntry("IIS://localhost/w3svc/apppools");

                //先检查是否已存在
                bool exists = false;
                DirectoryEntry exist_pool = null;
                foreach (DirectoryEntry pool in poolEntry.Children)
                {
                    //IIsApplicationPool表示应用程序池，Name即为名称
                    if (pool.Name.EqualsEx(poolName) && pool.SchemaClassName.EqualsEx("IIsApplicationPool"))
                    {
                        exist_pool = pool;
                        exists = true;
                        break;
                    }
                }
                //不存在才创建
                if (!exists)
                {
                    var pool = poolEntry.Children.Add(poolName, "IIsApplicationPool");
                    //如果指定标识，可以使用下面的方法，否则，可以直接执行 CommitChanges 方法：
                    // 0 = Local System（本地系统）
                    // 1 = Local Service（本地服务）
                    // 2 = Network Service（网络服务）
                    // 3 = Custom Identity（自定义配置）需要设置 WAMUserName 和 WAMUserPass 属性
                    pool.Properties["AppPoolIdentityType"][0] = 2;
                    pool.Properties["AppPoolAutoStart"].Value = true;
                    pool.Properties["MaxProcesses"][0] = 1;
                    pool.Properties["RapidFailProtection"].Value = false;
                    //pool.Properties["WAMUserName"].Value = poolName;
                    //pool.Properties["WAMUserPass"].Value = password;
                    /*
                     * 设置站点限制
                     */
                    if (cpulimit != "0")
                    {
                        pool.Properties["CPUAction"].Value = 1;
                        pool.Properties["CPULimit"].Value = Convert.ToInt32(cpulimit) * 1000;
                        pool.Properties["CPUResetInterval"].Value = 5;
                        pool.Properties["IdleTimeout"].Value = 20;
                    }
                    if (memeory != "0")
                    {
                        pool.Properties["PeriodicRestartMemory"].Value = Convert.ToInt32(memeory) * 1024;
                        pool.Properties["PeriodicRestartPrivateMemory"].Value = Convert.ToInt32(memeory) * 1024;
                        pool.Properties["PeriodicRestartTime"].Value = 180;

                    }
                    pool.CommitChanges();
                }
                else
                {
                    try
                    {
                        //如果指定标识，可以使用下面的方法，否则，可以直接执行 CommitChanges 方法：
                        // 0 = Local System（本地系统）
                        // 1 = Local Service（本地服务）
                        // 2 = Network Service（网络服务）
                        // 3 = Custom Identity（自定义配置）需要设置 WAMUserName 和 WAMUserPass 属性
                        exist_pool.Properties["AppPoolIdentityType"][0] = 2;
                        exist_pool.Properties["AppPoolAutoStart"].Value = true;
                        exist_pool.Properties["MaxProcesses"].Value = 1;
                        exist_pool.Properties["RapidFailProtection"].Value = false;
                        //exist_pool.Properties["WAMUserName"].Value = poolName;
                        //exist_pool.Properties["WAMUserPass"].Value = password;
                        /*
                         * 设置站点限制
                         */
                        if (cpulimit != "0")
                        {
                            exist_pool.Properties["CPUAction"].Value = 1;
                            exist_pool.Properties["CPULimit"].Value = Convert.ToInt32(cpulimit) * 1000;
                            exist_pool.Properties["CPUResetInterval"].Value = 5;
                            exist_pool.Properties["IdleTimeout"].Value = 20;
                        }
                        if (memeory != "0")
                        {
                            exist_pool.Properties["PeriodicRestartMemory"].Value = Convert.ToInt32(memeory) * 1024;
                            exist_pool.Properties["PeriodicRestartPrivateMemory"].Value = Convert.ToInt32(memeory) * 1024;
                            exist_pool.Properties["PeriodicRestartTime"].Value = 180;

                        }
                        exist_pool.CommitChanges();
                    }
                    catch
                    {
                        errorCode = ErrorCode.Unknown;
                    }
                }
            }
            catch
            {
                errorCode = ErrorCode.Unknown;
            }

            return errorCode;
        }

        public bool CreateAppPool_Q(string poolName, string password)
        {
            try
            {
                var poolEntry = new DirectoryEntry("IIS://localhost/w3svc/apppools");

                //先检查是否已存在
                bool exists = false;
                DirectoryEntry exist_pool = null;
                foreach (DirectoryEntry pool in poolEntry.Children)
                {
                    //IIsApplicationPool表示应用程序池，Name即为名称
                    if (pool.Name.EqualsEx(poolName) && pool.SchemaClassName.EqualsEx("IIsApplicationPool"))
                    {
                        exist_pool = pool;
                        exists = true;
                        break;
                    }
                }
                //不存在才创建
                if (!exists)
                {
                    var pool = poolEntry.Children.Add(poolName, "IIsApplicationPool");
                    //如果指定标识，可以使用下面的方法，否则，可以直接执行 CommitChanges 方法：
                    // 0 = Local System（本地系统）
                    // 1 = Local Service（本地服务）
                    // 2 = Network Service（网络服务）
                    // 3 = Custom Identity（自定义配置）需要设置 WAMUserName 和 WAMUserPass 属性
                    pool.Properties["AppPoolIdentityType"][0] = 2;
                    pool.Properties["AppPoolAutoStart"].Value = true;
                    pool.Properties["MaxProcesses"][0] = 1;
                    pool.Properties["RapidFailProtection"].Value = false;
                    //pool.Properties["WAMUserName"].Value = poolName;
                    //pool.Properties["WAMUserPass"].Value = password;
                    pool.CommitChanges();
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }

            return true; ;
        }

        public int RemoveAppPool(string poolName)
        {
            int errorCode = ErrorCode.Succeed;

            try
            {
                var poolEntry = new DirectoryEntry("IIS://localhost/w3svc/apppools");

                //找指定的应用程序池
                DirectoryEntry targetPool = null;
                foreach (DirectoryEntry pool in poolEntry.Children)
                {
                    if (pool.Name.EqualsEx(poolName) && pool.SchemaClassName.EqualsEx("IIsApplicationPool"))
                    {
                        targetPool = pool;
                        break;
                    }
                }

                //存在才移除
                if (targetPool != null)
                {
                    poolEntry.Children.Remove(targetPool);
                    poolEntry.CommitChanges();
                }
                else
                {
                    errorCode = ErrorCode.AppPoolNotFound;
                }
            }
            catch (Exception ex)
            {
                errorCode = ErrorCode.Unknown;
                Console.WriteLine(ex.Message);
            }

            return errorCode;
        }

        public int CreateDir(string siteName, string virtualPath, string physicalPath, bool enableAllMimeTypes)
        {
            int errorCode = ErrorCode.Succeed;

            try
            {
                var siteEntry = new DirectoryEntry("IIS://localhost/w3svc");

                //先找站点
                DirectoryEntry targetSite = null;
                foreach (DirectoryEntry site in siteEntry.Children)
                {
                    if (!site.SchemaClassName.EqualsEx("IIsWebServer"))
                        continue;

                    string name = Convert.ToString(site.Properties["ServerComment"].Value);
                    if (!name.IsNullOrEmpty() && name.EqualsEx(siteName))
                    {
                        targetSite = site;
                        break;
                    }
                }

                if (targetSite != null)
                {
                    //根目录
                    var rootEntry = new DirectoryEntry(string.Format("IIS://localhost/w3svc/{0}/ROOT", targetSite.Name));
                    bool exists = false;

                    foreach (DirectoryEntry dir in rootEntry.Children)
                    {
                        //IIsWebVirtualDir表示虚拟目录
                        if (!dir.SchemaClassName.EqualsEx("IIsWebVirtualDir"))
                            continue;

                        //名称不包含/，不会是多级
                        if (dir.Name.Equals(virtualPath.Substring(1)))
                        {
                            exists = true;
                            break;
                        }
                    }

                    if (!exists)
                    {
                        var dir = rootEntry.Children.Add(virtualPath.Substring(1), "IIsWebVirtualDir");
                        dir.Properties["Path"][0] = physicalPath;								//物理路径
                        dir.Properties["AppFriendlyName"][0] = virtualPath.Substring(1);		//名称
                        dir.Properties["AccessRead"][0] = true;									//读权限
                        dir.Properties["DontLog"][0] = true;

                        if (enableAllMimeTypes)
                        {
                            //new IISOle.MimeMapClass();
                            var mime = new IISOle.MimeMapClass();
                            mime.Extension = "*";
                            mime.MimeType = "application/octet-stream";
                            dir.Properties["MimeMap"].Clear();
                            dir.Properties["MimeMap"].Add(mime);
                        }

                        dir.CommitChanges();
                        rootEntry.CommitChanges();
                    }
                    else
                    {
                        errorCode = ErrorCode.AppExists;
                    }
                }
                else
                {
                    errorCode = ErrorCode.SiteNotFound;
                }
            }
            catch (Exception ex)
            {
                errorCode = ErrorCode.Unknown;
                Console.WriteLine(ex.Message);
            }

            return errorCode;
        }

        public int RemoveDir(string siteName, string virtualPath)
        {
            //移除虚拟目录的方法与移除应用程序一样
            return RemoveApp(siteName, virtualPath);
        }

        public int CreateApp(string siteName, string virtualPath, string physicalPath, string poolName, bool useSsl)
        {
            int errorCode = ErrorCode.Succeed;

            try
            {
                var siteEntry = new DirectoryEntry("IIS://localhost/w3svc");

                //启用ASP4
                this.EnableAspNet4(siteEntry);

                //先找站点
                DirectoryEntry targetSite = null;
                foreach (DirectoryEntry site in siteEntry.Children)
                {
                    if (!site.SchemaClassName.EqualsEx("IIsWebServer"))
                        continue;

                    string name = Convert.ToString(site.Properties["ServerComment"].Value);
                    if (!name.IsNullOrEmpty() && name.EqualsEx(siteName))
                    {
                        targetSite = site;
                        break;
                    }
                }

                if (targetSite != null)
                {
                    //根目录
                    var rootEntry = new DirectoryEntry(string.Format("IIS://localhost/w3svc/{0}/ROOT", targetSite.Name));
                    bool exists = false;

                    foreach (DirectoryEntry dir in rootEntry.Children)
                    {
                        if (!dir.SchemaClassName.EqualsEx("IIsWebDirectory") && !dir.SchemaClassName.EqualsEx("IIsWebVirtualDir"))
                            continue;

                        if (dir.Name.Equals(virtualPath.Substring(1)))
                        {
                            exists = true;
                            break;
                        }
                    }

                    if (!exists)
                    {
                        var dir = rootEntry.Children.Add(virtualPath.Substring(1), "IIsWebVirtualDir");
                        dir.Properties["Path"][0] = physicalPath;
                        dir.Properties["AppFriendlyName"][0] = virtualPath.Substring(1);
                        dir.Properties["AccessRead"][0] = true;
                        dir.Properties["AccessScript"][0] = true;			//脚本执行权限
                        dir.Properties["DontLog"][0] = true;

                        //处理poolName
                        if (!poolName.IsNullOrEmpty())
                            dir.Properties["AppPoolId"].Value = poolName;

                        //处理ssl
                        if (useSsl)
                            dir.Properties["AccessSSL"][0] = true;

                        //IIS6要处理通配符映射
                        string systemDir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
                        string scriptMap = string.Format("*,{0}\\Microsoft.NET\\Framework\\v4.0.30319\\aspnet_isapi.dll,0,GET,HEAD,POST", systemDir);
                        dir.Properties["ScriptMaps"].Add(scriptMap);

                        dir.Invoke("AppCreate", true);						//创建应用程序
                        dir.CommitChanges();
                        rootEntry.CommitChanges();
                    }
                    else
                    {
                        errorCode = ErrorCode.AppExists;
                    }
                }
                else
                {
                    errorCode = ErrorCode.SiteNotFound;
                }
            }
            catch (Exception ex)
            {
                errorCode = ErrorCode.Unknown;
                Console.WriteLine(ex.Message);
            }

            return errorCode;
        }

        public int RemoveApp(string siteName, string virtualPath)
        {
            int errorCode = ErrorCode.Succeed;

            try
            {
                var siteEntry = new DirectoryEntry("IIS://localhost/w3svc");

                //先找站点
                DirectoryEntry targetSite = null;
                foreach (DirectoryEntry site in siteEntry.Children)
                {
                    if (!site.SchemaClassName.EqualsEx("IIsWebServer"))
                        continue;

                    string name = Convert.ToString(site.Properties["ServerComment"].Value);
                    if (!name.IsNullOrEmpty() && name.EqualsEx(siteName))
                    {
                        targetSite = site;
                        break;
                    }
                }

                if (targetSite != null)
                {
                    //根目录
                    var rootEntry = new DirectoryEntry(string.Format("IIS://localhost/w3svc/{0}/ROOT", targetSite.Name));

                    DirectoryEntry targetApp = null;
                    foreach (DirectoryEntry app in rootEntry.Children)
                    {
                        if (!app.SchemaClassName.EqualsEx("IIsWebDirectory") && !app.SchemaClassName.EqualsEx("IIsWebVirtualDir"))
                            continue;

                        if (app.Name.EqualsEx(virtualPath.Substring(1)))
                        {
                            targetApp = app;
                            break;
                        }
                    }

                    if (targetApp != null)
                    {
                        rootEntry.Children.Remove(targetApp);
                        rootEntry.CommitChanges();
                    }
                    else
                    {
                        errorCode = ErrorCode.AppNotFound;
                    }
                }
                else
                {
                    errorCode = ErrorCode.SiteNotFound;
                }
            }
            catch (Exception ex)
            {
                errorCode = ErrorCode.Unknown;
                Console.WriteLine(ex.Message);
            }

            return errorCode;
        }

        public int SetCertificate(string siteName, string sslHash)
        {
            int errorCode = ErrorCode.Succeed;

            try
            {
                var siteEntry = new DirectoryEntry("IIS://localhost/w3svc");

                //找指定站点
                DirectoryEntry targetSite = null;
                foreach (DirectoryEntry site in siteEntry.Children)
                {
                    if (!site.SchemaClassName.EqualsEx("IIsWebServer"))
                        continue;

                    //站点名在ServerComment中
                    string name = Convert.ToString(site.Properties["ServerComment"].Value);
                    if (!name.IsNullOrEmpty() && name.EqualsEx(siteName))
                    {
                        targetSite = site;
                        break;
                    }
                }

                //存在才做后续处理
                if (targetSite != null)
                {
                    var hash = new object[sslHash.Length / 2];
                    for (int i = 0; i < sslHash.Length / 2; ++i)
                        hash[i] = sslHash.Substring(i * 2, 2);
                    targetSite.Properties["SSLCertHash"].Clear();
                    targetSite.Properties["SSLCertHash"].Add(hash);

                    targetSite.CommitChanges();
                }
                else
                {
                    errorCode = ErrorCode.SiteNotFound;
                }
            }
            catch (Exception ex)
            {
                errorCode = ErrorCode.Unknown;
                Console.WriteLine(ex.Message);
            }

            return errorCode;
        }

        public int SetPort(string siteName, int httpPort, int httpsPort)
        {
            int errorCode = ErrorCode.Succeed;

            try
            {
                var siteEntry = new DirectoryEntry("IIS://localhost/w3svc");

                //找指定站点
                DirectoryEntry targetSite = null;
                foreach (DirectoryEntry site in siteEntry.Children)
                {
                    if (!site.SchemaClassName.EqualsEx("IIsWebServer"))
                        continue;

                    //站点名在ServerComment中
                    string name = Convert.ToString(site.Properties["ServerComment"].Value);
                    if (!name.IsNullOrEmpty() && name.EqualsEx(siteName))
                    {
                        targetSite = site;
                        break;
                    }
                }

                //存在才做后续处理
                if (targetSite != null)
                {
                    if (httpPort > 0)
                        targetSite.Properties["ServerBindings"].Value = string.Format(":{0}:", httpPort);
                    if (httpsPort > 0)
                        targetSite.Properties["SecureBindings"].Value = string.Format(":{0}:", httpsPort);

                    targetSite.CommitChanges();
                }
                else
                {
                    errorCode = ErrorCode.SiteNotFound;
                }
            }
            catch (Exception ex)
            {
                errorCode = ErrorCode.Unknown;
                Console.WriteLine(ex.Message);
            }

            return errorCode;
        }

        protected int GetPort(string binding)
        {
            if (binding.IsNullOrEmpty())
                return 0;

            //IIS6的binding是“:80:”或者“local:80:”这样的形式
            int start = binding.IndexOf(":");
            int end = binding.IndexOf(":", start + 1);
            string port = binding.Substring(start + 1, end - start - 1);

            return Convert.ToInt32(port);
        }

        protected void EnableAspNet4(DirectoryEntry siteEntry)
        {
            try
            {
                siteEntry.Invoke("EnableWebServiceExtension", "ASP.NET v4.0.30319");
            }
            catch { }
        }
        /// <summary>
        /// 获取站点信息
        /// </summary>
        public List<string> GetSiteInfo()
        {
            DirectoryEntry rootentry = new DirectoryEntry("IIS://localhost/W3SVC");//创建IIS管理对象
            var poolEntry = new DirectoryEntry("IIS://localhost/w3svc/apppools");//pool
            var ftpEntry = new DirectoryEntry("IIS://localhost/MSFTPSVC");//IIS6管理对象

            int ServerCount = 0;

            /*
             * 获取站点数量
             */
            foreach (DirectoryEntry child in rootentry.Children)
            {
                if (child.SchemaClassName == "IIsWebServer")
                {
                    ServerCount += 1;
                }
            }

            //创建存储对象
            List<string> sitelist = new List<string>();//站点列表
            System.IO.DirectoryInfo directory;//创建路径对象
            string ServerComment = "";//站点描述
            string password = "";//站点密码
            string ServerPath = "";//站点目录
            string siteID = "";//站点ID
            long maxBands = 0;//最大绑定数
            long maxConnections = 0;//最大连接数
            string createTime = "";//站点创建时间
            string logPath = "";//日志文件存储路径
            string currentServerBindings;//绑定主机头IP端口字符串
            string[] currentBingdings = new string[2];//绑定主机头和端口
            string siteBindings = "";//当前站点绑定字串
            int BindingCount = 0;//站点绑定域名数
            string cpulimit = "";//CPU限制
            string memeory = "";//内存限制
            string netversion = "";//ASP.NET版本
            string sitestate = "";//站点状态
            string sitestype = "";//站点类型
            string phppath = "";//php path
            string homepages = "";//homepage
            string poolname = "";//应用程序池名

            try
            {
                /*
                * 循环站点获取站点信息
                */
                foreach (DirectoryEntry child in rootentry.Children)
                {
                    if (child.SchemaClassName == "IIsWebServer")
                    {
                        /*
                        * 获取站点标识符
                        */
                        siteID = child.Name.ToString();
                        /*
                         * 获取站点描述
                         */
                        ServerComment = child.Properties["ServerComment"].Value.ToString();
                        try //拿到应用池名
                        {
                            foreach (DirectoryEntry rootChild in child.Children)
                            {
                                if ((rootChild.SchemaClassName == "IIsWebVirtualDir") && (rootChild.Name.ToString().ToLower() == "root"))
                                {
                                    poolname = rootChild.Properties["AppPoolId"].Value.ToString();
                                }
                            }
                        }
                        catch
                        {

                        }
                        if (poolname == "")
                        {
                            poolname = ServerComment;
                        }
                        /*
                         * Password
                         */
                        password = child.Properties["AnonymousUserPass"].Value.ToString();
                        /*
                         * bands & connections
                         */
                        maxBands = Convert.ToInt64(child.Properties["MaxBandwidth"].Value) / 1024 / 1024;
                        if (maxBands < 0)
                        {
                            maxBands = 4095;
                        }
                        maxConnections = Convert.ToInt64(child.Properties["MaxConnections"].Value);
                        /*
                         * logdirectory
                         */
                        logPath = child.Properties["LogFileDirectory"].Value.ToString();
                        /*
                         * cpulimit & memeory
                         */
                        foreach (DirectoryEntry pool in poolEntry.Children)
                        {
                            //IIsApplicationPool表示应用程序池，Name即为名称
                            if (pool.Name.EqualsEx(poolname) && pool.SchemaClassName.EqualsEx("IIsApplicationPool"))
                            {
                                cpulimit = (Convert.ToInt32(pool.Properties["CPULimit"].Value) / 1000).ToString();
                                memeory = (Convert.ToInt32(pool.Properties["PeriodicRestartMemory"].Value) / 1024).ToString();
                            }
                        }
                        /*
                         * 获取绑定域名和端口
                         */
                        BindingCount = child.Properties["ServerBindings"].Count;
                        for (int count = 0; count < BindingCount; count++)
                        {
                            currentServerBindings = child.Properties["ServerBindings"][count].ToString();
                            currentBingdings.SetValue(currentServerBindings.Split(":".ToArray())[1], 0);
                            currentBingdings.SetValue(currentServerBindings.Split(":".ToArray())[2], 1);
                            if (currentBingdings[1] == "")
                            {
                                siteBindings += "localhost:" + currentBingdings[0] + ",";
                            }
                            else
                            {
                                siteBindings += currentBingdings[1] + ":" + currentBingdings[0] + ",";
                            }
                        }
                        //格式域名 消除最后的逗号
                        siteBindings = siteBindings.Substring(0, siteBindings.Length - 1);
                        /*
                         * sitestate
                         */
                        sitestate = "Started";
                        string autostart = "true";
                        try
                        {
                            autostart = child.Properties["ServerAutoStart"].Value.ToString().ToLower();
                        }
                        catch
                        {
                            autostart = "false";
                        }
                        if (autostart == "true")
                        {
                            try
                            {
                                child.Invoke("Start", new object[] { });
                                sitestate = "Started";
                            }
                            catch
                            {
                                sitestate = "Stopped";
                            }
                        }
                        /*
                         * sitetype
                         */
                        sitestype = "site";
                        /*
                         * 获取站点目录
                         */
                        foreach (DirectoryEntry rootChild in child.Children)
                        {
                            string name = rootChild.Name.ToString();
                            if ((rootChild.SchemaClassName == "IIsWebVirtualDir") && (rootChild.Name.ToString().ToLower() == "root"))
                            {
                                /*
                                * 获取首页
                                */
                                try
                                {
                                    homepages = rootChild.Properties["DefaultDoc"].Value.ToString();
                                }
                                catch
                                {
                                    homepages = "";
                                }
                                foreach (string scriptmap in rootChild.Properties["ScriptMaps"])
                                {
                                    if (scriptmap.Contains("v2.0"))
                                    {
                                        netversion = "v2.0";
                                        break;
                                    }
                                    if (scriptmap.Contains("v4.0"))
                                    {
                                        netversion = "v4.0";
                                        break;
                                    }
                                }
                                /*
                                 * php版本信息
                                 */
                                foreach (string scriptmap in rootChild.Properties["ScriptMaps"])
                                {
                                    if (scriptmap.Contains("php"))
                                    {
                                        phppath = scriptmap.Split(",".ToArray())[1];
                                        /* ---in---- */
                                        try
                                        {
                                            //phpisapi.dll
                                            if (Regex.IsMatch(phppath, "php[0-9]isapi.dll$"))
                                            {
                                                phppath = phppath.Substring(0, phppath.Length - 13) + "php-cgi.exe";
                                                //yvan_test
                                                File.AppendAllText(@"D:\1.txt",phppath + "\r\n");
                                            }
                                            // 判断IIS6的php引擎
                                            if (phppath.Contains("fcgiext.dll"))//如果是FastCGI引擎
                                            {
                                                string fastCgiPath = @"C:\WINDOWS\system32\inetsrv\fcgiext.dll";
                                                string fastiniPath = @"C:\WINDOWS\system32\inetsrv\fcgiext.ini";
                                                if (System.IO.File.Exists(fastCgiPath))
                                                {
                                                    //获取PHP路径
                                                    string siteid = siteID;
                                                    string phpcgi = INIOperationClass.INIGetStringValue(fastiniPath, "Types", "PHP:" + siteid, "");
                                                    if (phpcgi != "")
                                                    {
                                                        phppath = INIOperationClass.INIGetStringValue(fastiniPath, phpcgi, "ExePath", "");
                                                    }
                                                    else
                                                    {
                                                        //全局PHP路径
                                                        string gphpcgi = INIOperationClass.INIGetStringValue(fastiniPath, "Types", "PHP", "");
                                                        if (gphpcgi != "")
                                                        {
                                                            phppath = INIOperationClass.INIGetStringValue(fastiniPath, gphpcgi, "ExePath", "");
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    //doing nothing
                                                }
                                                //yvan_test
                                                File.AppendAllText(@"D:\1.txt", phppath + "\r\n");
                                            }
                                        }
                                        catch
                                        {
                                            //doing nothing
                                        }
                                        break;
                                    }
                                }
                                if (rootChild.Properties["Path"].Value == null)
                                {
                                    ServerPath = "";
                                }
                                else
                                {
                                    ServerPath = rootChild.Properties["Path"].Value.ToString();
                                }
                            }
                        }
                        /*
                        * 获取站点创建时间
                        */
                        if (Directory.Exists(ServerPath))
                        {
                            directory = new System.IO.DirectoryInfo(ServerPath);
                            createTime = directory.CreationTime.ToString("yyyy-MM-dd");
                        }
                        else
                        {
                            createTime = DateTime.Now.ToShortDateString().ToString();
                        }
                        /*
                         * 添加当前站点信息到列表
                         */
                        sitelist.Add(siteID + "-@-" + ServerComment + "-@-" + siteBindings + "-@-" + ServerPath + "-@-" + createTime + "-@-" + logPath + "-@-" + poolname + "-@-" + password + "-@-" + maxBands + "-@-" + maxConnections + "-@-" + cpulimit + "-@-" + memeory + "-@-" + netversion + "-@-" + sitestype + "-@-" + sitestate + "-@-" + phppath + "-@-" + homepages);
                        siteBindings = "";//初始化域名
                    }
                }
                /*
                 * FTP 
                 */
                foreach (DirectoryEntry ftpchild in ftpEntry.Children)
                {
                    if (!ftpchild.SchemaClassName.EqualsEx("IIsFtpServer"))		//IIsFtpServer代表FTP
                        continue;
                    siteID = ftpchild.Name.ToString();
                    ServerComment = ftpchild.Properties["ServerComment"].Value.ToString();
                    /*
                    * 获取绑定域名和端口
                    */
                    BindingCount = ftpchild.Properties["ServerBindings"].Count;
                    for (int count = 0; count < BindingCount; count++)
                    {
                        currentServerBindings = ftpchild.Properties["ServerBindings"][count].ToString();
                        currentBingdings.SetValue(currentServerBindings.Split(":".ToArray())[1], 0);
                        currentBingdings.SetValue(currentServerBindings.Split(":".ToArray())[2], 1);
                        if (currentBingdings[1] == "")
                        {
                            siteBindings += "localhost:" + currentBingdings[0] + ",";
                        }
                        else
                        {
                            siteBindings += currentBingdings[1] + ":" + currentBingdings[0] + ",";
                        }
                    }
                    //格式域名 消除最后的逗号
                    siteBindings = siteBindings.Substring(0, siteBindings.Length - 1);
                    var ftproot = ftpchild.Children.Find("ROOT", "IIsFtpVirtualDir");
                    ServerPath = ftproot.Properties["Path"].Value.ToString();
                    /*
                    * 获取站点创建时间
                    */
                    if (Directory.Exists(ServerPath))
                    {
                        directory = new System.IO.DirectoryInfo(ServerPath);
                        createTime = directory.CreationTime.ToString("yyyy-MM-dd");
                    }
                    else
                    {
                        createTime = DateTime.Now.ToShortDateString().ToString();
                    }
                    /*
                    * bands & connections
                    */
                    maxBands = Convert.ToInt64(ftpchild.Properties["MaxBandwidth"].Value) / 1024 / 1024;
                    maxConnections = Convert.ToInt64(ftpchild.Properties["MaxConnections"].Value);
                    /*
                         * sitestate
                         */
                    sitestate = "Started";
                    if (ftpchild.Properties["ServerAutoStart"].Value.ToString().ToLower() == "true")
                    {
                        try
                        {
                            ftpchild.Invoke("Start", new object[] { });
                            sitestate = "Started";
                        }
                        catch
                        {
                            sitestate = "Stopped";
                        }
                    }
                    /*
                     * sitetype
                     */
                    sitestype = "ftp";
                    /*
                     * 添加当前站点信息到列表
                     */
                    sitelist.Add(siteID + "-@-" + ServerComment + "-@-" + siteBindings + "-@-" + ServerPath + "-@-" + createTime + "-@-" + "" + "-@-" + "" + "-@-" + "" + "-@-" + maxBands + "-@-" + maxConnections + "-@-" + "" + "-@-" + "" + "-@-" + "" + "-@-" + sitestype + "-@-" + sitestate + "" + "");
                    siteBindings = "";//初始化域名
                }
            }
            catch (Exception ex)
            {
                //errorCode = ErrorCode.Unknown;
                Console.WriteLine(ex.Message);
            }
            return sitelist;
        }
        /// <summary>
        /// 获取新站点信息
        /// </summary>
        /// <param name="newsitename"></param>
        /// <returns></returns>
        public string GetNewSiteInfo(string newsitename)
        {
            DirectoryEntry rootentry = new DirectoryEntry("IIS://localhost/W3SVC");//创建IIS管理对象
            var poolEntry = new DirectoryEntry("IIS://localhost/w3svc/apppools");//pool
            var ftpEntry = new DirectoryEntry("IIS://localhost/MSFTPSVC");//IIS6管理对象

            //创建存储对象
            string newsite = "";//站点列表
            System.IO.DirectoryInfo directory;//创建路径对象
            string ServerComment = "";//站点描述
            string password = "";//站点密码
            string ServerPath = "";//站点目录
            string siteID = "";//站点ID
            long maxBands = 0;//最大绑定数
            long maxConnections = 0;//最大连接数
            string createTime = "";//站点创建时间
            string logPath = "";//日志文件存储路径
            string currentServerBindings;//绑定主机头IP端口字符串
            string[] currentBingdings = new string[2];//绑定主机头和端口
            string siteBindings = "";//当前站点绑定字串
            int BindingCount = 0;//站点绑定域名数
            string cpulimit = "";//CPU限制
            string memeory = "";//内存限制
            string netversion = "";//ASP.NET版本
            string sitestate = "";//站点状态
            string sitestype = "";//站点类型
            string phppath = "";//php path
            string homepages = "";//homepage
            string poolname = "";//应用程序池名

            try
            {
                /*
                * 循环站点获取站点信息
                */
                foreach (DirectoryEntry child in rootentry.Children)
                {
                    if (child.SchemaClassName == "IIsWebServer" && child.Properties["ServerComment"].Value.ToString() == newsitename)
                    {
                        /*
                        * 获取站点标识符
                        */
                        siteID = child.Name.ToString();
                        /*
                         * 获取站点描述
                         */
                        ServerComment = child.Properties["ServerComment"].Value.ToString(); ;
                        try //拿到应用池名
                        {
                            foreach (DirectoryEntry rootChild in child.Children)
                            {
                                if ((rootChild.SchemaClassName == "IIsWebVirtualDir") && (rootChild.Name.ToString().ToLower() == "root"))
                                {
                                    poolname = rootChild.Properties["AppPoolId"].Value.ToString();
                                }
                            }
                        }
                        catch
                        {

                        }
                        if (poolname == "")
                        {
                            poolname = ServerComment;
                        }
                        /*
                         * Password
                         */
                        password = child.Properties["AnonymousUserPass"].Value.ToString();
                        /*
                         * bands & connections
                         */
                        maxBands = Convert.ToInt64(child.Properties["MaxBandwidth"].Value) / 1024 / 1024;
                        if (maxBands < 0)
                        {
                            maxBands = 4095;
                        }
                        maxConnections = Convert.ToInt64(child.Properties["MaxConnections"].Value);
                        /*
                         * logdirectory
                         */
                        logPath = child.Properties["LogFileDirectory"].Value.ToString();
                        /*
                         * cpulimit & memeory
                         */
                        foreach (DirectoryEntry pool in poolEntry.Children)
                        {
                            //IIsApplicationPool表示应用程序池，Name即为名称
                            if (pool.Name.EqualsEx(poolname) && pool.SchemaClassName.EqualsEx("IIsApplicationPool"))
                            {
                                cpulimit = (Convert.ToInt32(pool.Properties["CPULimit"].Value) / 1000).ToString();
                                memeory = (Convert.ToInt32(pool.Properties["PeriodicRestartMemory"].Value) / 1024).ToString();
                            }
                        }
                        /*
                         * 获取绑定域名和端口
                         */
                        BindingCount = child.Properties["ServerBindings"].Count;
                        for (int count = 0; count < BindingCount; count++)
                        {
                            currentServerBindings = child.Properties["ServerBindings"][count].ToString();
                            currentBingdings.SetValue(currentServerBindings.Split(":".ToArray())[1], 0);
                            currentBingdings.SetValue(currentServerBindings.Split(":".ToArray())[2], 1);
                            if (currentBingdings[1] == "")
                            {
                                siteBindings += "localhost:" + currentBingdings[0] + ",";
                            }
                            else
                            {
                                siteBindings += currentBingdings[1] + ":" + currentBingdings[0] + ",";
                            }
                        }
                        //格式域名 消除最后的逗号
                        siteBindings = siteBindings.Substring(0, siteBindings.Length - 1);
                        /*
                         * sitestate
                         */
                        sitestate = "Started";
                        string autostart = "true";
                        try
                        {
                            autostart = child.Properties["ServerAutoStart"].Value.ToString().ToLower();
                        }
                        catch
                        {
                            autostart = "false";
                        }
                        if (autostart == "true")
                        {
                            try
                            {
                                child.Invoke("Start", new object[] { });
                                sitestate = "Started";
                            }
                            catch
                            {
                                sitestate = "Stopped";
                            }
                        }
                        /*
                         * sitetype
                         */
                        sitestype = "site";
                        /*
                         * 获取站点目录
                         */
                        foreach (DirectoryEntry rootChild in child.Children)
                        {
                            string name = rootChild.Name.ToString();
                            if ((rootChild.SchemaClassName == "IIsWebVirtualDir") && (rootChild.Name.ToString().ToLower() == "root"))
                            {
                                /*
                                * 获取首页
                                */
                                try
                                {
                                    homepages = rootChild.Properties["DefaultDoc"].Value.ToString();
                                }
                                catch
                                {
                                    homepages = "";
                                }
                                foreach (string scriptmap in rootChild.Properties["ScriptMaps"])
                                {
                                    if (scriptmap.Contains("v2.0"))
                                    {
                                        netversion = "v2.0";
                                        break;
                                    }
                                    if (scriptmap.Contains("v4.0"))
                                    {
                                        netversion = "v4.0";
                                        break;
                                    }
                                }
                                /*
                                 * php版本信息
                                 */
                                foreach (string scriptmap in rootChild.Properties["ScriptMaps"])
                                {
                                    if (scriptmap.Contains("php"))
                                    {
                                        phppath = scriptmap.Split(",".ToArray())[1];
                                        /* ---in---- */
                                        try
                                        {
                                            //phpisapi.dll
                                            if (Regex.IsMatch(phppath, "php[0-9]isapi.dll$"))
                                            {
                                                phppath = phppath.Substring(0, phppath.Length - 13) + "php-cgi.exe";
                                            }
                                            // 判断IIS6的php引擎
                                            if (phppath.Contains("fcgiext.dll"))//如果是FastCGI引擎
                                            {
                                                string fastCgiPath = @"C:\WINDOWS\system32\inetsrv\fcgiext.dll";
                                                string fastiniPath = @"C:\WINDOWS\system32\inetsrv\fcgiext.ini";
                                                if (System.IO.File.Exists(fastCgiPath))
                                                {
                                                    //获取PHP路径
                                                    string siteid = siteID;
                                                    string phpcgi = INIOperationClass.INIGetStringValue(fastiniPath, "Types", "PHP:" + siteid, "");
                                                    if (phpcgi != "")
                                                    {
                                                        phppath = INIOperationClass.INIGetStringValue(fastiniPath, phpcgi, "ExePath", "");
                                                    }
                                                    else
                                                    {
                                                        //全局PHP路径
                                                        string gphpcgi = INIOperationClass.INIGetStringValue(fastiniPath, "Types", "PHP", "");
                                                        if (gphpcgi != "")
                                                        {
                                                            phppath = INIOperationClass.INIGetStringValue(fastiniPath, gphpcgi, "ExePath", "");
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    //doing nothing
                                                }
                                            }
                                        }
                                        catch
                                        {
                                            //doing nothing
                                        }
                                        break;
                                    }
                                }
                                if (rootChild.Properties["Path"].Value == null)
                                {
                                    ServerPath = "";
                                }
                                else
                                {
                                    ServerPath = rootChild.Properties["Path"].Value.ToString();
                                }
                            }
                        }
                        /*
                        * 获取站点创建时间
                        */
                        if (Directory.Exists(ServerPath))
                        {
                            directory = new System.IO.DirectoryInfo(ServerPath);
                            createTime = directory.CreationTime.ToString("yyyy/MM/dd");
                        }
                        else
                        {
                            createTime = DateTime.Now.ToShortDateString().ToString();
                        }
                    }
                    /*
                     * 添加当前站点信息到列表
                     */
                    newsite = siteID + "-@-" + ServerComment + "-@-" + siteBindings + "-@-" + ServerPath + "-@-" + createTime + "-@-" + logPath + "-@-" + poolname + "-@-" + password + "-@-" + maxBands + "-@-" + maxConnections + "-@-" + cpulimit + "-@-" + memeory + "-@-" + netversion + "-@-" + sitestype + "-@-" + sitestate + "-@-" + phppath + "-@-" + homepages;
                }
            }
            catch (Exception ex)
            {
                //errorCode = ErrorCode.Unknown;
                Console.WriteLine(ex.Message);
            }
            return newsite;
        }

        public int CreateAppPool(string poolName)
        {
            int errorCode = ErrorCode.Succeed;
            try
            {
                ServerManager server = new ServerManager();//创建iis管理对象
                //先检查是否已存在
                bool exists = false;
                foreach (var pool in server.ApplicationPools)
                {
                    if (pool.Name.EqualsEx(poolName))
                    {
                        exists = true;
                        break;
                    }
                }

                //不存在才创建
                if (!exists)
                {
                    var appPool = server.ApplicationPools.Add(poolName);
                    appPool.ManagedRuntimeVersion = "v4.0";							//指定dotnet4.0，集成模式
                    appPool.ManagedPipelineMode = ManagedPipelineMode.Integrated;
                    appPool.QueueLength = 10000;
                    server.CommitChanges();
                }
                else
                {
                    errorCode = ErrorCode.AppPoolExists;
                }
            }
            catch (Exception ex)
            {
                errorCode = ErrorCode.Unknown;
                Console.WriteLine(ex.Message);
            }

            return errorCode;
        }
        /// <summary>
        /// 获取所有ftp站点信息
        /// </summary>
        /// <param name="newsitename"></param>
        /// <returns></returns>
        public List<string> GetFtpInfos()
        {
            return FtpUtil.iGetFtpInfos();
        }
        /// <summary>
        /// 删除ftp站点
        /// </summary>
        /// <param name="ftpname"></param>
        /// <returns></returns>
        public bool DeleteFtp(string ftpname)
        {

            return FtpUtil.DeleteQFtp(ftpname);
        }
        /// <summary>
        /// 获取站点路径
        /// </summary>
        /// <param name="sitename"></param>
        /// <returns></returns>
        public string GetSitePath(string sitename)
        {
            string ServerPath = "";//站点目录
            try
            {
                DirectoryEntry rootentry = new DirectoryEntry("IIS://localhost/W3SVC");//创建IIS管理对象
                /*
                * 循环站点获取站点信息
                */
                foreach (DirectoryEntry child in rootentry.Children)
                {
                    if (child.SchemaClassName == "IIsWebServer" && child.Properties["ServerComment"].Value.ToString() == sitename)
                    {
                        foreach (DirectoryEntry rootChild in child.Children)
                        {
                            string name = rootChild.Name.ToString();
                            if ((rootChild.SchemaClassName == "IIsWebVirtualDir") && (rootChild.Name.ToString().ToLower() == "root"))
                            {
                                if (rootChild.Properties["Path"].Value == null)
                                {
                                    ServerPath = "";
                                }
                                else
                                {
                                    ServerPath = rootChild.Properties["Path"].Value.ToString();
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                return "";
            }
            return ServerPath;
        }
        /// <summary>
        /// 获取所有站点名称
        /// </summary>
        /// <returns></returns>
        public List<string> GetSiteNames()
        {
            List<string> sitenames = new List<string>();//站点目录
            try
            {
                DirectoryEntry rootentry = new DirectoryEntry("IIS://localhost/W3SVC");//创建IIS管理对象
                /*
                * 循环站点获取站点信息
                */
                foreach (DirectoryEntry child in rootentry.Children)
                {
                    if (child.SchemaClassName == "IIsWebServer")
                    {
                        sitenames.Add(child.Properties["ServerComment"].Value.ToString());
                    }
                }
            }
            catch
            {
                return null;
            }
            return sitenames;
        }
        /// <summary>
        /// 删除FTP站点
        /// </summary>
        /// <returns></returns>
        public bool DeleteFtp(IUtil util, string ftpname)
        {
            return FtpUtil.DeleteQFtp(ftpname);
        }
        /// <summary>
        /// 判断FTP是否存在
        /// </summary>
        /// <param name="ftpname"></param>
        /// <returns></returns>
        public bool ExistsFtp(string ftpname)
        {
            FtpUtil ftputil = new FtpUtil();
            return ftputil.igetFtpState(ftpname);
        }
        /// <summary>
        /// 创建FTP
        /// </summary>
        /// <param name="ftpname"></param>
        /// <param name="ftppass"></param>
        /// <returns></returns>
        public int CreateFtp(string ftpname, string ftppass,string path)
        {
            int errorCode = ErrorCode.Succeed;
            FtpUtil ftputil = new FtpUtil();
            if(ftputil.igetFtpState(ftpname))
            {
               return ErrorCode.ftpExists; 
            }
            //创建FTP用户
            if (addsiteUtil.AddUser(ftpname, ftppass, System.Configuration.ConfigurationManager.AppSettings.Get("cusercomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cusergp")) == ErrorCode.UserNotAdd)
            {
                errorCode = ErrorCode.UserNotAdd;
                return errorCode;
            }

            var siteEntry = new DirectoryEntry("IIS://localhost/w3svc");//IIS6管理对象

            try
            {
                //检查是否已存在，顺便确定端口占用及站点ID占用情况
                var usedSiteIds = new List<int>();
                foreach (DirectoryEntry sitechild in siteEntry.Children)
                {
                    if (!sitechild.SchemaClassName.EqualsEx("IIsWebServer"))		//IIsWebServer代表站点
                        continue;

                    usedSiteIds.Add(Convert.ToInt32(sitechild.Name));			//站点的Name是SiteId
                }

                int ftpId = 0;//FTP ID
                for (ftpId = 1; ftpId < 65536; ++ftpId)
                {
                    if (!usedSiteIds.Contains(ftpId))
                        break;
                }
                //设置FTP站点权限
                addsiteUtil.icaclsSet(ftpname, path);
                //创建FTP
                return ftputil.icreateFtpPoint(ftpname, path, ftpId);

            }
            catch
            {
                return ErrorCode.ftpSiteFail;
            }
        }

        public int CreateFtp(bool rw,  string ftpname, string ftppass, string path)
        {
            int errorCode = ErrorCode.Succeed;
            FtpUtil ftputil = new FtpUtil();
            if (ftputil.igetFtpState(ftpname))
            {
                return ErrorCode.ftpExists;
            }
            //创建FTP用户
            if (addsiteUtil.AddUser(ftpname, ftppass, System.Configuration.ConfigurationManager.AppSettings.Get("cusercomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cusergp")) == ErrorCode.UserNotAdd)
            {
                errorCode = ErrorCode.UserNotAdd;
                return errorCode;
            }

            var siteEntry = new DirectoryEntry("IIS://localhost/w3svc");//IIS6管理对象

            try
            {
                //检查是否已存在，顺便确定端口占用及站点ID占用情况
                var usedSiteIds = new List<int>();
                foreach (DirectoryEntry sitechild in siteEntry.Children)
                {
                    if (!sitechild.SchemaClassName.EqualsEx("IIsWebServer"))		//IIsWebServer代表站点
                        continue;

                    usedSiteIds.Add(Convert.ToInt32(sitechild.Name));			//站点的Name是SiteId
                }

                int ftpId = 0;//FTP ID
                for (ftpId = 1; ftpId < 65536; ++ftpId)
                {
                    if (!usedSiteIds.Contains(ftpId))
                        break;
                }
                //设置FTP站点权限
                addsiteUtil.icaclsSet(ftpname, path);
                //创建FTP
                return ftputil.icreateFtpPoint(ftpname, path, ftpId);

            }
            catch
            {
                return ErrorCode.ftpSiteFail;
            }
        }



        #region 创建伪静态配置
        public int CreateRewriteRule(string sitename, string sitepath)
        {
            int errorCode = ErrorCode.Succeed;
            DirectoryEntry site = null;// 当前站点
            var siteEntry = new DirectoryEntry("IIS://localhost/w3svc");//IIS6管理对象
            try
            {
                /*
                 * 判断伪静态配置是否存在
                 */
                bool rewrite_flag = false;
                foreach (DirectoryEntry sitechild in siteEntry.Children)
                {
                    if (sitechild.SchemaClassName.EqualsEx("IIsWebServer") && sitechild.Properties["ServerComment"].Value.ToString() == sitename)
                    {
                        site = sitechild;
                        foreach (DirectoryEntry filtersChild in sitechild.Children)
                        {
                            if (filtersChild.SchemaClassName == "IIsFilters")
                            {
                                foreach (DirectoryEntry filterChild in filtersChild.Children)
                                {
                                    if (filterChild.SchemaClassName == "IIsFilter")
                                    {
                                        if (filterChild.Properties["FilterPath"].Value.ToString().ToLower().Contains("rewrite"))
                                        {
                                            rewrite_flag = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (rewrite_flag == true)
                {
                    return ErrorCode.SiteExists;//配置存在 
                }
                //创建others文件夹
                if (sitepath.EndsWith("wwwroot"))
                {
                    string temp = sitepath.Substring(0, sitepath.LastIndexOf("wwwroot") - 1);
                    if (!Extensions.EqualsRootPath(temp))
                    {
                        sitepath = temp;
                    }
                }
                string rewritedllpath = sitepath + "\\others";
                if (!System.IO.Directory.Exists(rewritedllpath))
                {
                    try
                    {
                        System.IO.Directory.CreateDirectory(rewritedllpath);
                    }
                    catch
                    {
                        return ErrorCode.IOEXCEPTION;//创建路径失败
                    }
                }
                //添加Everyone权限
                AddSiteUtil addsiteUtil = new AddSiteUtil();
                addsiteUtil.icaclsSet("Everyone", rewritedllpath);
                //复制Rewrite.dll到others
                string yrootpath = System.Environment.CurrentDirectory;
                string rewrite_dll_frompath = yrootpath + "/data/" + "Rewrite.dll";
                string rewrite_dll_topath = System.IO.Path.Combine(@rewritedllpath, System.IO.Path.GetFileName(@rewrite_dll_frompath));
                try
                {
                    System.IO.File.Copy(@rewrite_dll_frompath, rewrite_dll_topath, true);
                }
                catch
                {
                    return ErrorCode.VirtualDirNotFound;//Rewrite.dll文件不存在
                }
                //创建伪静态配置
                DirectoryEntry filters = null;
                try
                {
                    filters = site.Children.Find("Filters", "IIsFilters");
                    filters.Properties["FilterLoadOrder"].Value = ",rewrite";
                }
                catch
                {
                    if (filters == null)
                    {
                        //创建Filters
                        filters = site.Children.Add("Filters", "IIsFilters");
                        filters.Properties["FilterLoadOrder"].Value = ",rewrite";
                    }
                }
                DirectoryEntry filter = filters.Children.Add("rewrite", "IIsFilter");
                filter.Properties["FilterEnabled"].Value = "TRUE";
                filter.Properties["FilterPath"].Value = rewrite_dll_topath;
                filter.CommitChanges();
                filters.CommitChanges();
                siteEntry.CommitChanges();
            }
            catch
            {
                errorCode = ErrorCode.CommitFail;//意外错误
            }
            return errorCode;//返回结果
        }
        #endregion

        #region 删除用户-回滚
        public int DeleteSiteUsers()
        {
            /*----- errorCode ----*/
            int errorCode = ErrorCode.CommitOK;
            DirectoryEntry rootentry = new DirectoryEntry("IIS://localhost/W3SVC");//创建IIS管理对象
            try
            {
                /*
                * 循环站点获取站点信息
                */
                foreach (DirectoryEntry child in rootentry.Children)
                {
                    if (child.SchemaClassName == "IIsWebServer")
                    {
                        /*
                         * 获取站点描述
                         */
                        string ServerComment = child.Properties["ServerComment"].Value.ToString();
                        try
                        {
                            /*---- 删除站点用户 ----*/
                            if (ADUser.ExistUser(ServerComment))
                            {
                                ADUser.RemoveGroupUser(System.Configuration.ConfigurationManager.AppSettings.Get("cusergp"), ServerComment);
                            }
                            /*---- 删除应用池用户 ----*/
                            if (ADUser.ExistUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + ServerComment))
                            {
                                ADUser.RemoveGroupUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolgp"), System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + ServerComment);
                            }
                        }
                        catch
                        {

                        }
                    }
                }
            }
            catch
            {
                errorCode = ErrorCode.CommitFail;
            }
            /*--- return ----*/
            return errorCode;
        }
        #endregion

        #region add 301 httpredirect
        public int HttpRedirectAdd(string source_url, string target_url, string sitename)
        {
            /*--- errorCode ----*/
            int errorCode = ErrorCode.CommitOK;
            try//try
            {
                /*--- get redirect sites ----*/
                DirectoryEntry rootentry = new DirectoryEntry("IIS://localhost/W3SVC");//创建IIS管理对象
                //sitename
                string current_sitename = "";
                bool redirectexists_flag = false;
                //iterator
                foreach (DirectoryEntry child in rootentry.Children)
                {
                    if (child.SchemaClassName == "IIsWebServer")
                    {
                        //sitename
                        current_sitename = child.Properties["ServerComment"].Value.ToString();
                        //compare
                        if (current_sitename.StartsWith(System.Configuration.ConfigurationManager.AppSettings.Get("redirectname")))
                        {
                            foreach (DirectoryEntry rootChild in child.Children)
                            {
                                //root
                                if ((rootChild.SchemaClassName == "IIsWebVirtualDir") && (rootChild.Name.ToString().ToLower() == "root"))
                                {
                                    if (rootChild.Properties["HttpRedirect"].Value == null)
                                    {
                                        break;
                                    }
                                    else
                                    {
                                        //path
                                        string current_httpRedirect = rootChild.Properties["HttpRedirect"].Value.ToString();
                                        try//try
                                        {
                                            //regular
                                            string destination = current_httpRedirect.Substring(0, current_httpRedirect.IndexOf(","));
                                            if (destination == target_url)//IO
                                            {
                                                //exists
                                                redirectexists_flag = true;
                                                break;
                                            }
                                        }
                                        catch
                                        {

                                        }
                                    }
                                }
                            }
                        }
                        //break
                        if (redirectexists_flag)
                        {
                            break;
                        }
                    }
                }
                //exists
                if (redirectexists_flag)
                {
                    try//try
                    {
                        //bind domain
                        foreach (DirectoryEntry child in rootentry.Children)
                        {
                            if (child.SchemaClassName == "IIsWebServer" && child.Properties["ServerComment"].Value.ToString() == current_sitename)
                            {
                                child.Properties["ServerBindings"].Add(string.Format(":{0}:{1}", "80", source_url));
                                child.CommitChanges();
                            }
                        }
                    }
                    catch
                    {
                        errorCode = ErrorCode.saveNewSiteFail;
                    }
                }
                else//not exists
                {
                    //add new redirect site
                    if (!CreateRedirectSite(sitename, source_url, target_url))
                    {
                        errorCode = ErrorCode.siteStateError;
                    }                    
                }
            }
            catch
            {
                errorCode = ErrorCode.CommitFail;
            }
            return errorCode;
        }
        /// <summary>
        /// jduge redirect rule exists or no
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private bool RedirectExists(string path, string target_url)
        {
            try//try
            {
                //xmlhelper
                XmlHelper xmlHelper = new XmlHelper(path);
                string xpath_redirect = @"//configuration/system.webServer/httpRedirect";
                //get destination
                string destination = xmlHelper.GetAttributeValue(xpath_redirect, "destination");
                //compare
                if (destination == target_url)
                {
                    return true;
                }
                //no
                return false;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// add redirect site
        /// </summary>
        /// <param name="siteinfo"></param>
        /// <returns></returns>
        public bool CreateRedirectSite(string sitename, string source_url, string target_url)
        {
            try//try
            {
                //entry
                var siteEntry = new DirectoryEntry("IIS://localhost/w3svc");//IIS6管理对象
                //path
                string redirect301_path = System.Configuration.ConfigurationManager.AppSettings.Get("redirectpath") + @"\" + sitename;
                string redirectpath = System.Configuration.ConfigurationManager.AppSettings.Get("redirectname");
                string redirectname = redirectpath.Substring(0, redirectpath.Length - 1);
                /*
                 * 创建用户
                 */
                if (addsiteUtil.UserExist(System.Configuration.ConfigurationManager.AppSettings.Get("cusergp"), redirectname) != ErrorCode.UserExist)
                {
                    if (addsiteUtil.AddUser_Q(redirectname, System.Configuration.ConfigurationManager.AppSettings.Get("redirectpass"), System.Configuration.ConfigurationManager.AppSettings.Get("redirectcomm"), System.Configuration.ConfigurationManager.AppSettings.Get("cusergp")) == ErrorCode.UserNotAdd)
                    {
                        return false;
                    }
                }
                /*
                 * 创建目录
                 */
                try
                {
                    //create path
                    if (!System.IO.Directory.Exists(redirect301_path))
                    {
                        System.IO.Directory.CreateDirectory(redirect301_path);
                        /*---- hide ----*/
                        addsiteUtil.icaclsSet(redirectname, redirect301_path);//icacls
                        System.IO.File.SetAttributes(System.Configuration.ConfigurationManager.AppSettings.Get("redirectpath"), System.IO.FileAttributes.Hidden);
                        System.IO.File.SetAttributes(redirect301_path, System.IO.FileAttributes.Hidden);
                    }
                }
                catch
                {
                    //create disk c path
                    try
                    {
                        //path
                        redirect301_path = "C:" + System.Configuration.ConfigurationManager.AppSettings.Get("redirectpath").Substring(2) + @"\" + sitename;
                        //create path
                        if (!System.IO.Directory.Exists(redirect301_path))
                        {
                            System.IO.Directory.CreateDirectory(redirect301_path);
                            /*---- hide ----*/
                            addsiteUtil.icaclsSet(redirectname, redirect301_path);//icacls
                            System.IO.File.SetAttributes(System.Configuration.ConfigurationManager.AppSettings.Get("redirectpath"), System.IO.FileAttributes.Hidden);
                            System.IO.File.SetAttributes(redirect301_path, System.IO.FileAttributes.Hidden);
                        }
                    }
                    catch
                    {
                        return false;
                    }
                }
                /*
                * 创建站点
                */
                try
                {
                    //启用ASP4
                    this.EnableAspNet4(siteEntry);

                    //检查是否已存在，顺便确定端口占用及站点ID占用情况
                    var usedSiteIds = new List<int>();
                    var usedHttpPorts = new List<int>();
                    var usedHttpsPorts = new List<int>();
                    foreach (DirectoryEntry sitechild in siteEntry.Children)
                    {
                        if (!sitechild.SchemaClassName.EqualsEx("IIsWebServer"))		//IIsWebServer代表站点
                            continue;
                        try
                        {
                            usedSiteIds.Add(Convert.ToInt32(sitechild.Name));			//站点的Name是SiteId
                        }
                        catch
                        {

                        }
                    }

                    //确定可用的站点id
                    int siteId = 0;
                    for (siteId = 1; siteId < 65536; ++siteId)
                    {
                        if (!usedSiteIds.Contains(siteId))
                            break;
                    }
                    //建站
                    var site = siteEntry.Children.Add(siteId.ToString(), "IIsWebServer");

                    //设置绑定等信息
                    site.Properties["ServerBindings"].Add(string.Format(":{0}:{1}", "80", source_url));

                    site.Properties["ServerComment"].Value = sitename;
                    site.Properties["AccessScript"][0] = true;		//允许脚本执行
                    site.Properties["AccessRead"][0] = true;		//允许读
                    site.Properties["LogType"].Value = "0";			//记录日志
                    //建根目录
                    var root = site.Children.Add("ROOT", "IIsWebVirtualDir");
                    site.Properties["AuthFlags"].Value = "1";
                    root.Properties["Path"].Value = redirect301_path;
                    root.Properties["AppIsolated"].Value = "1";
                    root.Properties["AppRoot"].Value = "/LM/W3SVC/" + siteId + "/Root";
                    root.Properties["HttpRedirect"].Value = target_url + "," + "EXACT_DESTINATION, PERMANENT";
                    root.Properties["AnonymousUserName"].Value = redirectname;//这里是系统用户  
                    root.Properties["AnonymousUserPass"].Value = System.Configuration.ConfigurationManager.AppSettings.Get("redirectpass");//对应的密码  
                    /*
                    * 设置站点访问权限
                    */
                    //site.Properties["AnonymousUserName"].Value = redirectname;//这里是系统用户  
                    //site.Properties["AnonymousUserPass"].Value = System.Configuration.ConfigurationManager.AppSettings.Get("redirectpass");//对应的密码  
                    root.Properties["AppFriendlyName"].Value = redirectname;//用户的友好显示  
                    //提交更改
                    site.CommitChanges();
                    root.CommitChanges();
                    siteEntry.CommitChanges();
                    try
                    {
                        site.Invoke("Start", new object[] { });//启动站点
                    }
                    catch
                    {
                        
                    }
                }
                catch
                {
                    /*
                     * 撤销更改
                     */
                    siteEntry.Dispose();
                    return false;
                }
                /*
                * 将新建的站点数据存储到数据库表
                */
                IISAdoHelper.adoSaveNewSite(sitename);

                return true;
            }
            catch 
            {
                return false;
            }     
        }
        #endregion
    }
}
